What Does array_values Do?

The array_values function takes an associative array or an array with custom keys and returns a new array with all values re-indexed starting from 0.

When working with PHP, the array_values function is a quick and convenient way to re-index an array. But what if you’re restricted from using built-in array functions or want to understand the underlying concept? In this guide, we’ll implement the functionality of array_values manually.

Example:

$input = ['a' => 'apple', 'b' => 'banana', 'c' => 'cherry'];
$output = array_values($input);
// Output: ['apple', 'banana', 'cherry']

Manual Implementation of array_values in PHP

Here’s how to achieve the same result without using array_values or any other array-related functions:

Example:

function manualArrayValues($array) {
    $result = [];
    foreach ($array as $key => $value) {
        $result[] = $value;
    }
    return $result;
}

// Test Case
$input = ['x' => 'xylophone', 'y' => 'yarn', 'z' => 'zebra'];
$output = manualArrayValues($input);

// Output
print_r($output);

Output:

Array
(
    [0] => xylophone
    [1] => yarn
    [2] => zebra
)

How It Works:

  1. Loop Through the Array:
    Using a foreach loop, traverse each key-value pair of the input array.
  2. Append Values:
    Add each value to a new array $result using the [] operator, ensuring the keys are ignored.
  3. Return the Result:
    The $result array now holds the re-indexed values, replicating the behavior of array_values.

Why Avoid Built-in Functions?

  • Learning Opportunity: Helps you understand how PHP handles arrays internally.
  • Custom Use Cases: In environments where built-in functions are restricted, this knowledge can be invaluable.

Keep Learning 🙂

Leave a Reply

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