Home > Article > Backend Development > PHP array slicing preserves key names
By specifying the fourth parameter preserve_keys as true, the array_slice() function can preserve the key names of PHP associative array slices: Preserve key names: Specify preserve_keys as true. Syntax: array_slice(array, offset, length, preserve_keys). Practical case: Use an example to show how to retain the key names of associative array slices.
PHP array slice that retains the key name
PHP array slice functionarray_slice()
will be reset by default Program key names. However, we can preserve the key names by specifying the fourth parameter preserve_keys
as true
.
Grammar:
array_slice(array $array, int $offset, int $length, bool $preserve_keys = FALSE)
Practical case:
Suppose we have a file named $fruits
An associative array where the key is the name of the fruit and the value is the number of fruits. We want to get a slice of two elements starting at index 1 while retaining the key names:
$fruits = array('apple' => 2, 'banana' => 3, 'orange' => 5, 'pear' => 1); $slice = array_slice($fruits, 1, 2, true); print_r($slice);
Output:
Array ( [banana] => 3 [orange] => 5 )
As we can see, the $slice
array retains The key name of the original array.
The above is the detailed content of PHP array slicing preserves key names. For more information, please follow other related articles on the PHP Chinese website!