Sort an Array
Sorts indexed scalar values in ascending natural case-insensitive order.
Purpose
Sorts indexed scalar values in ascending natural case-insensitive order.
Snippet details
ContextArrayLevelProductionCopy-and-paste statusMarked safe after review.Categories
- Forms and Validation
Code
<?php
/*
* Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
* Free for personal and internal use. Paid project use requires visible credit
* to Jeffery L. Paris. Corporate use requires a paid license fee unless a
* separate written license states otherwise.
*/
/**
* Sort an Array.
*
* Purpose:
* Sorts indexed scalar values and reindexes the array.
*
* @param array $values Values to sort.
* @return array Sorted values.
*/
function ogSnippetSortAnArray(array $values): array {
$clean_values = array();
foreach ($values as $value) {
if (is_scalar($value) === true) {
$clean_values[] = (string) $value;
}
}
sort($clean_values, SORT_NATURAL | SORT_FLAG_CASE);
return $clean_values;
}
$sorted_ships = ogSnippetSortAnArray(array('Serenity', 'Enterprise', 'Rocinante'));
echo 'First sorted ship: '.$sorted_ships[0];