Toolbox
Toolbox

Reputation: 2491

Extract key from multidimensional array

Need to extract a key string (within an multidimensional array) and store in a variable.

<?php

$data = [
  ["Toyota" => [1,2,3]],
];

print_r($data);

$extracted_key = $data[0][0];
echo $extracted_key;

Expected result:

Toyota

Upvotes: 0

Views: 181

Answers (2)

Umer Abbas
Umer Abbas

Reputation: 1876

This should work for any number of arrays on level 2

$data = [
  ["Toyota" => [1,2,3]],
];

foreach($data as $key=>$arr){
    $keys = array_keys($data[$key]);
    foreach($keys as $val){
        echo "$val\r\n";
    }

}

Upvotes: 0

RiggsFolly
RiggsFolly

Reputation: 94682

Using array_keys() will dig that out for you

print_r(array_keys($data[0])[0]);

Not sure how useful this will be in the long run though

Upvotes: 1

Related Questions