Suppose we have an array:
$array = [
0 => 'apple',
1 => 'banana',
3 => 'tangerine',
5 => 'Grape'
];
You can see that the keys of the array are 0, 1, 3, and 5, and there is a disconnection in the middle. If we iterate through this array, although the value is normal, if we rely on key values, unexpected results may be produced.
The function of the array_values function is to return all values in the array and re-index these values. The key names will be incremented from 0 to ensure that the keys of the array are continuous numbers.
Syntax example:
array_values(array $array): array
The return value is a new array containing all the values of the original array, but the key name is reindexed.
For the above discontinuous key array, we use array_values to process:
<?php
$array = [
0 => 'apple',
1 => 'banana',
3 => 'tangerine',
5 => 'Grape'
];
$cleanArray = array_values($array);
print_r($cleanArray);
Output result:
Array
(
[0] => apple
[1] => banana
[2] => tangerine
[3] => Grape
)
Through array_values , we successfully change the array keys to consecutive 0, 1, 2, and 3.
When you delete elements in the middle of the array through some operations, the key names are not continuous.
It is necessary to conduct index traversal of the array (such as for loops), and continuous numeric keys are more convenient.
Pass an array to a function or interface that requires continuous numeric keys.
Non-continuous arrays returned by user input or process database queries need to be cleaned.
If you return the following array through interface or database query (for example, the result obtained by json_decode):
<?php
$apiResponse = [
2 => 'Tom',
4 => 'Jerry',
7 => 'Spike'
];
You need to turn it into an array that can be processed directly:
$cleaned = array_values($apiResponse);
foreach ($cleaned as $key => $name) {
echo "serial number {$key},Name:{$name}" . PHP_EOL;
}
Output:
serial number 0,Name:Tom
serial number 1,Name:Jerry
serial number 2,Name:Spike
array_values is an easy and efficient way to rebuild array indexes in PHP.
Applicable to arrays whose key names are not continuous or need to be reset after they are deleted.
After reindexing the array, it can avoid a lot of traversal and logical judgment complexity.
If you want to know more PHP skills, please visit:
<a href="https://gitbox.net/php-array-functions">PHPArray functions</a>