Get the first key of an array in php

Created at 03-Apr-2021 , By samar

Get the first key of an array in php

With this article, we will examine several different instances of how to solve the "Get the first key of an array in php".

  • 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);
    

    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

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.