Question

I would like to know if it is possible to get the x-value position (ie 2nd) in a variable variable array reference.

the code below works for the 1st array but not the 2nd.

// WORKS FINE //
$my1stArray= array( 'red', 'green', 'blue');
$var_1st = 'my1stArray';

// for each lopp of var var works fine
echo " - my1stArray Values - <br>";
foreach ($$var_1st as $k => $v){
echo $k." : ".$v." <br>";
}
// direct access also works
echo "my1stArray 3rd value: ".${$var_1st}[2]."<br>";

// Not so good! //
$my2ndArray = array(
    'color' => '#ff0000',
    'face' => 'helvetica',
    'size' => '+5',
);
$var_2nd = 'my2ndArray';

// for each lopp of var_2nd works fine
echo "<br> - my2ndArray Values - <br>";
foreach ($$var_2nd as $k => $v){
echo $k." : ".$v." <br>";
}
/** try to access 2nd value in array with position **/
echo "my2ndArray 2rd value: ".${$var_2nd[1]}[0]."<br>";
echo "my2ndArray 2rd value: ".${$var_2nd}[1][0]."<br>";
Was it helpful?

Solution

Well, in the comments I said "no, you can't", but there is actually a way. Here is an example (without variable variables):

$my2ndArray = array(
    'color' => '#ff0000',
    'face' => 'helvetica',
    'size' => '+5',
);
$keys = array_keys($my2ndArray);
echo "my2ndArray 2nd value: " . $my2ndArray[$keys[1]]  . "<br>";

Doesn't look very nice, but should work. Not that if you ever sort the array, the key indexes will change.

Another way to do that would be using a counter and a loop as I mentioned in the comments. But that would be even uglier...

OTHER TIPS

Your last example in your code is not working for the same reason that the following code does not work:

$a = array('akey'=>'a','bkey'=>'b');
echo $a[0];

The reason is the key is set to a string and must be accessed as such. To fix my example I would need to change it to:

$a = array('akey'=>'a','bkey'=>'b');
echo $a['akey'];

To fix your example you need to change your last echo so that it references the key as a string:

echo "my2ndArray 2rd value: ".${$var_2nd}['color']."<br>";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top