Mike Harrison Mike Harrison - 3 months ago 11
PHP Question

Create variable from each item in PHP array

I would like to step through a PHP array and create a variable for each entry in it. My array ($array) looks like this:

Array
(
[0] => Array
(
[first_name] => Arthur
[last_name] => Dent
[planet] => Earth
)

[1] => Array
(
[first_name] => Ford
[last_name] => Prefect
[planet] => Betelgeuse
)

)


I have got the following:

$0_first_name = $array['0']['first_name'];
$0_last_name = $array['0']['last_name'];


But this is pretty time consuming, and means I need to explicitly declare each one and then can't allow for extra entries within the array at each level.

I would like to know what is the best way of doing this please.

Thanks for the help

Mike

Answer

Something like this should do what I think you are trying to do.

$data=array(
    array('first_name'=>'Arthur','last_name'=>'Dent','planet'=>'Earth'),
    array('first_name'=>'Ford','last_name'=>'Prefect','planet'=>'Betelgeuse')
);

foreach( $data as $i => $arr ){
    foreach( $arr as $key => $value ){
        ${$key.$i}=$value;
        ${$i.'_'.$key}=$value;
    }
}
echo $first_name0, $first_name1, ${'0_first_name'};

Obviously I have the integer after the name but it's trivial to reverse them and have something like $0first_name or $0_first_name - but they need to be handled differently when outputting them - ${'1_first_name'} etc - again, as has been pointed out - not the best approach for maintainability so now I'll go off and rethink all the bad decisions I have made in life.

Comments