Viewed   327 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

$check1="some value"

$check2="some value"

$check3="some value"

$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?



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;
Friday, October 14, 2022

You could use get_defined_vars() to find the name of a variable that has the same value as the one you're trying to find the name of. Obviously this will not always work, since different variables often have the same values, but it's the only way I can think of to do this.

Edit: get_defined_vars() doesn't seem to be working correctly, it returns 'var' because $var is used in the function itself. $GLOBALS seems to work so I've changed it to that.

function print_var_name($var) {
    foreach($GLOBALS as $var_name => $value) {
        if ($value === $var) {
            return $var_name;

    return false;

Edit: to be clear, there is no good way to do this in PHP, which is probably because you shouldn't have to do it. There are probably better ways of doing what you're trying to do.

Friday, September 9, 2022

Job #1 when you have a problem with code that is generating HTML, is look at the output source and compare it with what you expect. I've had problems like this before and they usually vanished when I stopped thinking about the PHP code, and looked at the actual output.

What is the content of $productImg1URL - and if the images that it's referencing are in the URL starting /images/ - does that start $productImg1URL. If it's just the name of an image, but without the path - you have to put that into place.

Monday, November 28, 2022

Use ${'varname'} syntax:

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

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

Saturday, September 24, 2022

They should just roll over:


$var1 = "TEST";


echo $var1; //Outputs TEST
Friday, August 5, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :