Thursday, 30 August 2018

PHP extracts multidimensional associative array keys as text


With a basic associative array like:


$ar = array("First" => 1, "Second" , "Third" =>"Three");

if you do:
foreach($ar as $key => $val) {

  var_dump($key);

}

This will produce:
string 'First' (length=5)

int 0

string 'Third' (length=5)

How do you Achieve the same results in a Multidimensional Array?
Something like:
array( 0 => array(
            "First" => 1, "Two", "Third" => "Three"
                )
     );

I tried:
foreach($ar as $k => $v){

        var_dump($ar[0][$k]);
        }

I got:
string 'Two' (length=3)

Instead of:
string 'First' (length=5)

    int 0

    string 'Third' (length=5)

Thanx

If $ar is equal to this:
array( 0 => array(
        "First" => 1, "Two", "Third" => "Three"
            )
 );

You could iterate over the inner array to get the same result:
foreach ($ar as $k => $v) {
    foreach ($v as $k2 => $v2) {
            var_dump($k2);
    }
}

Output:
string(5) "First"
  int(0)
string(5) "Third"

0 comments:

Post a Comment