How to Create a Custom PHP Function for Retrieving Array Keys Without Built-In Functions

The array_keys function in PHP retrieves all the keys from an array. Below is a custom implementation of this functionality without using PHP’s built-in array functions.

Code Example:

<?php
function custom_array_keys($array) {
    $keys = []; // Initialize an empty array to store the keys

    // Loop through the array
    foreach ($array as $key => $value) {
        $keys[] = $key; // Add the key to the keys array
    }

    return $keys;
}

// Example usage
$array = ['a' => 1, 'b' => 2, 'c' => 3];
$keys = custom_array_keys($array);

print_r($keys);
?>

Output:

Array
(
    [0] => a
    [1] => b
    [2] => c
)

Explanation:

  1. Input Parameter:
    • $array: The array from which keys will be extracted.
  2. Result Initialization:
    • Create an empty array $keys to store the keys.
  3. Loop Through the Array:
    • Use a foreach loop to iterate over the array.
    • For each element, retrieve the key and append it to the $keys array.
  4. Return Value:
    • Return the $keys array containing all the keys of the input array.

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *