How to use array_key_first function in PHP

1 Answer

0 votes
/*
    Demonstration of array_key_first() in PHP

    ---------------------------------------------------------
    What does array_key_first() do?
    ---------------------------------------------------------
    - It returns the FIRST KEY of an array.
    - It does NOT modify the array's internal pointer.
    - It works with associative arrays, numeric arrays, and mixed arrays.
    - If the array is empty, it returns NULL.

    This makes it safer and cleaner than using reset() when
    you only need the first key and do NOT want to change
    the array's internal pointer.
*/

// ---------------------------------------------------------
// Example 1: Associative array
// ---------------------------------------------------------
$user = [
    "name" => "R2D2",
    "age"  => 97,
    "city" => "LA"
];

// Get the first key
$firstKeyUser = array_key_first($user);

// Explanation printed to screen
echo "Example 1: Associative array\n";
echo "The first key in \$user is: $firstKeyUser\n\n";


// ---------------------------------------------------------
// Example 2: Numeric (indexed) array
// ---------------------------------------------------------
$numbers = [10, 20, 30];

// First key will be 0
$firstKeyNumbers = array_key_first($numbers);

echo "Example 2: Numeric array\n";
echo "The first key in \$numbers is: $firstKeyNumbers\n\n";


// ---------------------------------------------------------
// Example 3: Mixed array (numeric + associative)
// ---------------------------------------------------------
$mixed = [
    5 => "apple",
    "color" => "red",
    10 => "banana"
];

// First key is 5 because it appears first in the array definition
$firstKeyMixed = array_key_first($mixed);

echo "Example 3: Mixed array\n";
echo "The first key in \$mixed is: $firstKeyMixed\n\n";


// ---------------------------------------------------------
// Example 4: Empty array
// ---------------------------------------------------------
$empty = [];

// array_key_first() returns NULL for empty arrays
$firstKeyEmpty = array_key_first($empty);

echo "Example 4: Empty array\n";
var_dump($firstKeyEmpty); // Shows NULL
echo "\n";



/*
run:

Example 1: Associative array
The first key in $user is: name

Example 2: Numeric array
The first key in $numbers is: 0

Example 3: Mixed array
The first key in $mixed is: 5

Example 4: Empty array
NULL

*/

 



answered Jun 20 by avibootz
...