PHP array_values() Function

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 RepresentationVisual Representation of PHP array_values() Function

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.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.