PHP’s array_values() Function

In the realm of PHP programming, arrays are a fundamental data structure, allowing developers to organize and manipulate data efficiently. Among the myriad of array functions PHP offers, array_values() stands out as a simple yet powerful tool. In this blog, we will delve into the world of array_values(), exploring its purpose, usage, and practical examples.

Understanding array_values()

array_values() is a versatile PHP function used to extract all the values from an array and return them as a new indexed array. It is particularly handy when you need to re-index an array or want to access the values while discarding the keys. This function effectively ‘resets’ the keys, providing you with a clean slate to work with your array data.

The Syntax
The syntax of array_values() is quite straightforward:

array_values(array $input): array

Here, $input is the array from which you want to extract values. The function returns an indexed array containing all the values from the input array.

Practical Usage
1. Resetting Array Keys
Imagine you have an associative array, and you want to reset the keys to start from 0, creating a numerically indexed array. array_values() makes this transformation a breeze:

$associativeArray = [
‘apple’ => ‘red’,
‘banana’ => ‘yellow’,
‘grape’ => ‘purple’
];
$numericalArray = array_values($associativeArray);
print_r($numericalArray);

Output:

Array
(
[0] => red
[1] => yellow
[2] => purple
)

2. Removing Keys
Sometimes, you might want to work with the values of an array without concerning yourself with the keys. For instance, when performing operations like sorting or filtering, keys can become irrelevant. array_values() is your go-to function:

$data = [
5 => ‘five’,
2 => ‘two’,
9 => ‘nine’
];
$valuesOnly = array_values($data);
print_r($valuesOnly);

Output:

Array
(
[0] => five
[1] => two
[2] => nine
)

3. Creating Copies
Sometimes, you may want to work with a copy of an array, especially if you plan to make changes without affecting the original. array_values() can help you create a new array with the same values:

$original = [10, 20, 30];
$copy = array_values($original);
$copy[] = 40;
echo ‘Original: ‘ . implode(‘, ‘, $original) . “\n”;
echo ‘Copy: ‘ . implode(‘, ‘, $copy);

Output:

Original: 10, 20, 30
Copy: 10, 20, 30, 40

 

Closure
“array_values()” is a small but invaluable tool in your PHP arsenal. Whether you need to reset array keys, work with values independently, or create copies, this function simplifies your code and streamlines array manipulation. Incorporate it into your PHP projects to harness its simplicity and efficiency, making your code cleaner and more maintainable.