Get the first key of an array in php

Answers 1
  • Get the first key of an array using array_key_first() function

    <?php
        $array = ['first_key' => 1, 'second_key' => 2, 'third_key' => 3];
    
        if (!function_exists('array_key_first')) {
            function array_key_first(array $array) {
                foreach($array as $key => $unused) {
                        return $key;
                }
                return NULL;
            }
        }
    
       $firstKey = array_key_first($array);
       var_dump($firstKey);
    
    0

    Using this code snippet you will get the first key of an array in php. It returns the first key of array if array is not empty else it returns null. This  function in php will get the first key from an array without affecting the internal array pointer.

  • Back to code snippet queries related php