PHP array_values() function returns all the values from an array. This function indexes the array numerically.
Syntax
array_values($array)
Parameters
array(required): It is an input array.
Return value
This method returns an array with the fetched values.
Visual Representation
Example 1: How to Use array_values() function
<?php
$arr = [
'a' => 'Apple',
'b' => 'Microsoft',
'c' => 'Amazon',
'd' => 'Alphabet',
'e' => 'Meta'];
echo 'Before array_values() function: ';
print_r($arr);
echo 'After array_values() function: ';
print_r(array_values($arr));
Output
Before array_values() function: Array
(
[a] => Apple
[b] => Microsoft
[c] => Amazon
[d] => Alphabet
[e] => Meta
)
After array_values() function: Array
(
[0] => Apple
[1] => Microsoft
[2] => Amazon
[3] => Alphabet
[4] => Meta
)
In this example, the function returns an array containing the values from $arr. The output is : [‘Apple’, ‘Microsoft’, ‘Amazon’, ‘Alphabet’, ‘Meta’].
Just a warning that re-indexing an array by array_values() may cause you to reach the memory limit unexpectedly.
The array_keys() and array_values() are very closely related functions. The first function returns an array of all the keys, and the second returns all the values.
For example, consider you had an array with user IDs as keys and usernames as values; you could use array_keys() to generate an array where the values were the keys.
That’s it.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.