phparraysmultidimensional-array

Get the first key of the first row if a 2d 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

Solution

  • 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