It is an in-built function in PHP that is used to show element values of a given array in a new array. PHP array_values function creates a new array in which it stores only values of elements from a given array and by default gives the numerical keys to every single value.
Table of Contents
Syntax
array_values($array);
Parameters
PHP array_values function takes only one parameter from which it will store the values.
Let’s try the examples.
Example 1
<?php
$arr=array("Name"=>"Ali","Age"=>"20","Country"=>"Pakistan");
echo "<pre>";
print_r(array_values($arr));
echo "</pre>";
?>
In the above example, we declared an associative array, and then we used the array_values() function.
Output
Array
(
[0] => Ali
[1] => 20
[2] => Pakistan
)
Now you can see a new array has been created and only values are showing in it.
What if we declare an index array with an array value function? See the example below.
Example 2
<?php
$arr = ['One', 'Two', 'Three', 'four', 'five'];
echo "<pre>";
print_r(array_values($arr));
echo "</pre>";
?>
Output
Array
(
[0] => One
[1] => Two
[2] => Three
[3] => four
[4] => five
)
As you can see from the output that’s how it works with the index array, the array_values() function assign every single value a numerical key.
Example 3 – Multi-Dimensional Array
<?php
$emp = [
'name' => 'memon',
'email' => '[email protected]',
'phone' => '1234567890',
'hobbies' => ['reading', 'Tennis'],
'profiles' => ['facebook' => 'memonfb', 'instagram' => 'memoninst']
];
echo "<pre>";
print_r(array_values($emp));
echo "</pre>";
?>
In the above example, we declared a multidimensional array and then used the Array_values() function let’s check out the results.
Output
Array
(
[0] => memon
[1] => [email protected]
[2] => 1234567890
[3] => Array
(
[0] => reading
[1] => Tennis
)
[4] => Array
(
[facebook] => memonfb
[instagram] => memoninst
)
)
See how the information is printed, first of all, it printed the first three values and assigns them index keys then on the no:3 index key it printed the array value, and then on no:4 another array value is printed, the Array_values() function printed the whole array values while keeping their index keys in sequential order.
Conclusion
In this tutorial, we learned about the array_values function, see the definition, and then discuss some examples.
Suggested Articles: