Search code examples
phparraysvariable-variables

Curly brace variable in array name, PHP


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.


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