Question

I know there are a lot of similar questions on here, and I think I've read them all. My problem is that I am attempting to loop through a list of arrays and grab one value from each. The arrays have been set up by a third party, and I don't have the access to configure how I am receiving them. Here's what I have so far:

for ($i = 0; $i < $length; $i++) {

    // Both of these work and return the value I need
    echo $post->related_credits_0_related_show[0]; 
    echo "{$post->related_credits_0_related_show[0]}"

    // But none of these do, and I need to loop through a handful of arrays
    echo "{$post->related_credits_{$i}_related_show[0]}";
    echo "{$post->related_credits_${i}_related_show[0]}";
    echo "{$post->related_credits_{${i}}_related_show[0]}";
    echo "{$post->related_credits_".$i."_related_show[0]}";

}

I've tried many (many!) more combinations that I won't include. I've also tried converting $i to a string. Been knocking my head against this for awhile.

Thanks ahead of time for any help.

Was it helpful?

Solution

You can use this:

$varname = "related_credits_$i_related_show";
$array =  $post->$varname;
echo $array[0]; 

A shorter form would be:

$post->{"related_credits_{$i}_related_show"}[0];

Here you find all about so called "variable variables" : http://www.php.net/manual/en/language.variables.variable.php

OTHER TIPS

You need to use variable variables here. The basic usage is as follows:

$var = 'Hello there!';
$foo = 'var';
echo $$foo;
     ^^--- note the double $-sign

This will output:

Hello there!

Instead of $$foo, you can also write the following:

echo ${"$foo"};

If the variable name is more complex, you can can also do:

echo ${"some_stuff_{$foo}_more_stuff"};

In this case, the string that denotes the variable name contains a variable, and that variable is also wrapped inside curly braces ({}). This is done in order to avoid problems with constants, array indexes etc. But if your use-case doesn't involve any of those, you don't have to worry about it.

For your specific problem, you can use the following:

for ($i=0; $i < $length; $i++) { 
    $post->{"related_credits_{$i}_related_show"}[0];
}

Or, if you prefer concatenation:

for ($i=0; $i < $length; $i++) { 
    $res = $post->{'related_credits_'.$i.'_related_show'}[0];
}

See the documentation on Variable Variables for more information.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top