PHP array_values() - Get All Array Values
The array_values() function in PHP is a straightforward but powerful array utility that extracts all the values from an array and returns them with numeric keys starting from zero. This tutorial will walk you through everything you need to know about the array_values() function, including practical examples, best practices, common mistakes, and relevant interview questions. Whether you are reindexing arrays or simply want to retrieve values while discarding keys, array_values() can be very useful in your PHP array handling.
Prerequisites
- Basic knowledge of PHP language syntax
- Understanding of arrays and their key-value structure in PHP
- PHP 5 or later installed on your system (array_values() is available in all modern PHP versions)
Setup Steps
To follow along with the examples, ensure you have a PHP environment ready. You can use:
- Local development server: XAMPP, MAMP, Local by Flywheel, or PHP built-in server
- Online PHP Sandbox: Websites like onlinephp.io or 3v4l.org
Create a test.php file or open your PHP sandbox to try the below examples.
Understanding PHP array_values()
The array_values() function takes an array as input and returns a new array containing all the values of the original array, but with newly indexed numeric keys beginning at 0. This means that any original keys (associative or numeric) are discarded.
array array_values(array $array)
Parameters:
$array: The input array from which values will be extracted.
Returns: An indexed array of array values starting with index 0.
Practical Examples
Example 1: Simple Indexed Array
<?php
$fruits = ['apple', 'banana', 'orange'];
$values = array_values($fruits);
print_r($values);
?>
Output:
Array
(
[0] => apple
[1] => banana
[2] => orange
)
Since the array already has numeric keys starting at 0, array_values() returns the identical array.
Example 2: Associative Array
<?php
$user = [
"name" => "Alice",
"email" => "alice@example.com",
"age" => 25
];
$values = array_values($user);
print_r($values);
?>
Output:
Array
(
[0] => Alice
[1] => alice@example.com
[2] => 25
)
Here, the keys 'name', 'email', and 'age' are lost, and the values are reindexed starting from zero.
Example 3: Mixed Keys and Reindexing
<?php
$mixedArray = [
5 => 'five',
3 => 'three',
10 => 'ten'
];
$reindexed = array_values($mixedArray);
print_r($reindexed);
?>
Output:
Array
(
[0] => five
[1] => three
[2] => ten
)
This is useful when you want to reset the keys of an array with non-sequential numeric keys.
Example 4: Using array_values() to extract values before JSON encoding
<?php
$data = [
"id" => 101,
"title" => "PHP Tutorial",
"author" => "Bob"
];
// Return only the values for JSON client without keys
$jsonValues = json_encode(array_values($data));
echo $jsonValues;
?>
Output:
["101","PHP Tutorial","Bob"]
Best Practices
- Use for reindexing: Use
array_values()when you want to reset the array keys after filtering or other operations that remove items. - Preserve keys explicitly: If you want to preserve keys along with values,
array_values()should not be used, since it reindexes numerically. - Avoid unnecessary calls: Donβt wrap arrays that already have numeric keys starting at zero in
array_values()as it consumes resources without changes. - Combine with array_filter(): Use
array_values()after filtering arrays witharray_filter()since filtering preserves keys.
Common Mistakes
- Expecting keys to be preserved: Remember
array_values()always resets keys; it doesnβt keep original keys. - Passing non-arrays: Passing anything other than an array will cause warnings or errors.
- Confusing with array_keys():
array_keys()returns keys,array_values()returns values.
Interview Questions
Junior Level
- Q1: What does
array_values()do in PHP?
A: It returns all values from an array with numeric keys starting from 0, discarding the original keys. - Q2: If you pass an associative array to
array_values(), are keys preserved?
A: No, the keys are lost, and a new numeric index starting at 0 is created. - Q3: What type of keys does
array_values()generate?
A: Numeric keys starting from 0 sequentially. - Q4: Can
array_values()be used to filter keys?
A: No, it only extracts values and reindexes numeric keys. - Q5: What will
array_values()return if passed an empty array?
A: It will return an empty array.
Mid Level
- Q1: How can
array_values()be useful after usingarray_filter()?
A: Sincearray_filter()preserves keys,array_values()can be used to reindex the array with sequential numeric keys. - Q2: What is the difference between
array_values()andarray_keys()?
A:array_values()returns the values from the array, whilearray_keys()returns the keys. - Q3: Can
array_values()handle multi-dimensional arrays?
A: Yes, but it only reindexes at the first array level; inner arrays remain unchanged. - Q4: Does
array_values()modify the original array?
A: No, it returns a new array and does not affect the original. - Q5: What happens if you pass a non-array type to
array_values()?
A: PHP will generate a warning or error since the argument must be an array.
Senior Level
- Q1: Explain a scenario where using
array_values()can optimize data processing in PHP.
A: After filtering or deleting elements in arrays, usingarray_values()reindexes the array to prevent unexpected bugs when using functions expecting sequential numeric keys, improving data consistency. - Q2: How does
array_values()behave internally when working with large arrays in terms of performance?
A:array_values()iterates over the entire array to copy values and assign new numeric keys, which has O(n) time complexity; for very large arrays, this overhead might impact performance. - Q3: Can
array_values()be used safely in multithreaded PHP environments?
A: Yes, sincearray_values()returns a new array without modifying the original, it is thread-safe. - Q4: How would you combine
array_values()with array mapping functions to restructure data?
A: You can first extract array values witharray_values(), then usearray_map()to apply transformations cleanly on reindexed values. - Q5: Is it possible to preserve associative keys while using
array_values()? If not, what alternatives exist?
A: No,array_values()always resets keys. To preserve keys, avoid usingarray_values()or use functions likearray_filter()with callbacks that maintain keys.
FAQ
Q: Does array_values() work with objects?
A: No, array_values() requires an array input. Passing objects will cause an error.
Q: Can I use array_values() to order an array by value?
A: No, array_values() only extracts values and resets keys; to order an array by value, use sorting functions like asort() or usort().
Q: Why do I use array_values() after filtering an array?
Because filtering with array_filter() usually preserves original keys, which can cause issues if you expect zero-based continuous indexes. Using array_values() fixes this by reindexing numeric keys.
Q: Is it possible to pass multidimensional arrays to array_values()?
Yes, but array_values() only works on the top-level array. Inner arrays remain as is unless you apply array_values() recursively.
Q: How is array_values() different from casting an array to (array) type?
array_values() extracts values and reindexes numeric keys, whereas casting to (array) simply ensures the variable is an array type without any modification to keys or values.
Conclusion
The PHP array_values() function is a useful tool when you need to extract all values from an array and reset keys with sequential numeric indexes starting at 0. It plays a vital role in array reindexing, especially after filtering or manipulating arrays. By understanding how it works, when to use it, and its limitations, you can write cleaner and more predictable PHP code with better array handling. Practice the examples provided and apply the function appropriately to simplify tasks involving PHP arrays.