Arrays are a commonly used and essential data type in PHP. In real-world development, we often need to manipulate the values within arrays. The array_values() function is a handy tool for this purpose; it retrieves all values from an array and returns a new indexed array.
The basic syntax of the function is as follows:
array_values(array $array): array
Parameter details:
<?php // Define an associative array $student = [ "name" => "Zhang San", "age" => 18, "gender" => "Male" ]; // Use array_values() function to get the values from the array $values = array_values($student); // Print the new indexed array print_r($values); ?>
Array ( [0] => Zhang San [1] => 18 [2] => Male )
From the example above, the array_values() function extracts all values from the associative array and creates a new indexed array. The new array's keys start at 0 and increment by 1, discarding the original keys.
This function is ideal when you need to work with array values without caring about the keys, simplifying the process of handling array data.
The array_values() function is a convenient way in PHP to retrieve array values. Whether you’re restructuring data or iterating over values, it helps developers quickly obtain a clean, numerically indexed list of array values, improving code clarity and efficiency.