Home » Php » Return PHP array name

Return PHP array name

Posted by: admin July 12, 2020 Leave a comment

Questions:
Array ( [kanye] => Array ( [0] => Kanya [1] => Janaye [2] => Kayne [3] => Kane [4] => Kaye ) [wst] => Array ( [0] => ST [1] => St [2] => st [3] => EST [4] => West ) )

Array
(
    [0] => Kanya
    [1] => Janaye
    [2] => Kayne
    [3] => Kane
    [4] => Kaye
)
Array
(
    [0] => ST
    [1] => St
    [2] => st
    [3] => EST
    [4] => West
)

I’ve got those two arrays inside one array. The top array holds them both, then below is each one individually. When I am displaying the individual arrays, how do I echo their name?

So the first would be kanye, then list the contents, etc.

Hope that makes sense. I know it will be a simple bit of code but it’s stumping me.

How to&Answers:

You can use a foreach statement to get the key value pair of the array:

$outer_arr = array('kanye' => array('Kanya', 'Janaye', 'Kayne', 'Kane'));
foreach($outer_arr as $key => $val) {
    print($key); // "kanye"
    print_r($val); // Array ( [0] => Kanya [1] => Janaye [2] => Kayne [3] => Kane )
}

Answer:

If you just need to get the keys, you can use array_keys

$myArray = array(
    "Kanye" => array("Kane", ...)
    "West" => array("Wst", ...)
);

print_r(array_keys($myArray));
/*
array (
    0 => Kanye
    1 => West
)
*/

Answer:

How about just print_r on the outer array?