Asked  7 Months ago    Answers:  5   Viewed   71 times

I have a PHP for loop:

for ($counter=0,$counter<=67,$counter++){

echo $counter;
$check="some value";

}

What I am trying to achieve is use the for loop variable and append it to the name of another variable.

Bascially, I want the PHP output to be as follows for each row

1
$check1="some value"

2
$check2="some value"

3
$check3="some value"

4
$check4="some value"

etc etc 

I have tried $check.$counter="some value" but this fails.

How can I achieve this? Am I missing something obvious?

 Answers

35

The proper syntax for variable variables is:

${"check" . $counter} = "some value";

However, I highly discourage this. What you're trying to accomplish can most likely be solved more elegantly by using arrays. Example usage:

// Setting values
$check = array();
for ($counter = 0; $counter <= 67; $counter++){
    echo $counter;
    $check[] = "some value";
}

// Iterating through the values
foreach($check as $value) {
    echo $value;
}
Wednesday, March 31, 2021
 
innovation
answered 7 Months ago
38

You need to open the file for edit, seek to the desired position and then write to the file, eg.:

<?php
  $file = fopen($filename, "c");
  fseek($file, -3, SEEK_END);
  fwrite($file, "whatever you want to write");
  fclose($file);
?>

Further reference at php.net - fseek doc

Hope that helps.

Friday, May 28, 2021
 
jsuggs
answered 5 Months ago
98

Like this:

var str = 'blah blah blah';
str += ' blah';

str += ' ' + 'and some more blah';
Thursday, June 10, 2021
 
relyt
answered 5 Months ago
65

Use ${'varname'} syntax:

for($i=1; $i <= 5; $i++) {
    ${'file' . $i} = $i;
}

However, it's often better to use arrays instead of this.

Friday, July 16, 2021
 
Silfverstrom
answered 4 Months ago
49

You need stub files in order for PhpStorm to understand what DS (a PHP extension written in C) offers (classes/functions/etc).

Stub file is basically a PHP version of that -- just "declaration/documentation" part -- e.g. function declarations but with empty bodies. You can either make your own ... or find some existing ones (if somebody else did it already, of course).

A bit more on stub files in general:

  • https://stackoverflow.com/a/15775431/783119
  • https://stackoverflow.com/a/30329412/783119

So .. basically what you need is php-ds/polyfill -- "You should also include the polyfill in your project for compatibility and IDE integration" .

IDE will read such files and will understand what real DS extension has to offer/what it does (type of parameters/returns/etc).

Friday, August 20, 2021
 
ahmelsayed
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :