Mike Harrison Mike Harrison - 1 year ago 80
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:

[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


Answer Source

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


foreach( $data as $i => $arr ){
    foreach( $arr as $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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download