How can you display the sorted values of an array in PHP using foreach() or array_values()?
To display the sorted values of an array in PHP using foreach() or array_values(), you can first sort the array using a sorting function like sort(), asort(), or ksort(). Then, you can use either a foreach loop to iterate over the sorted array and display each value, or use array_values() to get a new array containing only the values in the sorted order.
// Original array
$array = [4, 2, 7, 1, 5];
// Sort the array
sort($array);
// Using foreach to display sorted values
foreach($array as $value) {
echo $value . " ";
}
// Using array_values() to get sorted values
$sortedValues = array_values($array);
print_r($sortedValues);
Keywords
Related Questions
- What is the significance of using date_create and the DateTime class in PHP for handling dates?
- What are the potential issues with using readfile() in PHP for downloading large files and how can they be mitigated?
- How can mod_rewrite in PHP be effectively used to redirect URLs with parameters to cleaner, more user-friendly URLs?