This explains useful functions for efficiently sorting and manipulating arrays in PHP in an easy-to-understand way. Master the basic operations frequently used in daily tasks such as sorting arrays, adding and deleting elements, and searching to improve your PHP programming skills.

Basic PHP Array Sorting Functions (sort, rsort, asort, ksort)

PHP provides several functions for sorting arrays.
The four basic functions you should especially remember are the following.

  • sort()
    Sorts the array values in ascending order. Keys are reassigned.
  • rsort()
    Sorts the array values in descending order. Keys are also reassigned.
  • asort()
    Sorts the array values in ascending order while maintaining the keys.
  • ksort()
    Sorts the array by keys in ascending order.

Example

$array = ['b' => 3, 'a' => 1, 'c' => 2];

// sort() - Sort values in ascending order; keys are reassigned
sort($array);
print_r($array);
// Output: [1, 2, 3]

// rsort() - Sort values in descending order; keys are reassigned
rsort($array);
print_r($array);
// Output: [3, 2, 1]

// asort() - Sort values in ascending order; keys are maintained
$array = ['b' => 3, 'a' => 1, 'c' => 2];
asort($array);
print_r($array);
// Output: ['a' => 1, 'c' => 2, 'b' => 3]

// ksort() - Sort keys in ascending order
$array = ['b' => 3, 'a' => 1, 'c' => 2];
ksort($array);
print_r($array);
// Output: ['a' => 1, 'b' => 3, 'c' => 2]

How to Use Functions for Adding and Removing Array Elements (array_push, array_pop, array_shift, array_unshift, unset)

These functions are commonly used to dynamically add or remove elements from arrays.

  • array_push()
    Adds elements to the end of the array.
  • array_pop()
    Removes and returns the last element of the array.
  • array_shift()
    Removes and returns the first element of the array.
  • array_unshift()
    Adds elements to the beginning of the array.
  • unset()
    Removes the element of the specified key.

Example

$array = [1, 2, 3];

// array_push
array_push($array, 4);
print_r($array); // [1, 2, 3, 4]

// array_pop
$last = array_pop($array);
echo $last; // 4

// array_shift
$first = array_shift($array);
echo $first; // 1

// array_unshift
array_unshift($array, 0);
print_r($array); // [0, 2, 3]

// unset
unset($array[1]);
print_r($array); // [0, 3] (Element with key 1 is removed; keys are not reindexed)

// Note: Even if you remove elements with unset, keys are not reassigned. Use array_values() to reindex keys if necessary.

Useful Functions to Search and Extract Elements from Arrays (in_array, array_search, array_filter)

Use these when searching for elements that meet specific conditions within an array.

  • in_array()
    Checks if a specified value exists in an array (returns a boolean).
  • array_search()
    Returns the key of a specified value (returns false if not found).
  • array_filter()
    Uses a callback function to extract only elements that meet certain conditions.

Example

$array = [10, 20, 30, 40];

// in_array
if (in_array(20, $array)) {
    echo "20 was found";
}

// array_search
$key = array_search(30, $array);
echo "30 is at key {$key}";

// array_filter
$result = array_filter($array, function($value) {
    return $value > 25;
});
print_r($result); // [30, 40]

Sorting and Manipulating Multidimensional Arrays (array_multisort, usort)

With multidimensional arrays, it is often necessary to sort by multiple criteria.

  • array_multisort()
    Sorts multiple arrays or array columns together.
  • usort()
    Sorts array elements using a custom comparison function.

Example of array_multisort

$data = [
  ['name' => 'Taro', 'score' => 70],
  ['name' => 'Jiro', 'score' => 85],
  ['name' => 'Saburo', 'score' => 70],
];

$scores = array_column($data, 'score');
$names = array_column($data, 'name');

// Sort by score ascending, then name ascending
array_multisort($scores, SORT_ASC, $names, SORT_ASC, $data);

echo "<pre>";
print_r($data);
echo "</pre>";

Output:
Array
(
    [0] => Array
        (
            [name] => Saburo
            [score] => 70
        )

    [1] => Array
        (
            [name] => Taro
            [score] => 70
        )

    [2] => Array
        (
            [name] => Jiro
            [score] => 85
        )

)

Example of usort

$data = [
    ['name' => 'Taro', 'score' => 70],
    ['name' => 'Jiro', 'score' => 85],
    ['name' => 'Saburo', 'score' => 70],
];

// Custom comparison function to sort by score ascending; if scores are equal, sort by name ascending
usort($data, function($a, $b) {
    if ($a['score'] === $b['score']) {
        return strcmp($a['name'], $b['name']);  // Compare names ascending
    }
    return $a['score'] <=> $b['score'];  // Compare scores ascending
});

echo "<pre>";
print_r($data);
echo "</pre>";

Output:
Array
(
    [0] => Array
        (
            [name] => Saburo
            [score] => 70
        )

    [1] => Array
        (
            [name] => Taro
            [score] => 70
        )

    [2] => Array
        (
            [name] => Jiro
            [score] => 85
        )

)

Tips and Precautions for Efficient PHP Array Manipulation (array_map, array_reduce, array_walk)

Using higher-order functions is recommended for efficient array processing.

  • array_map()
    Applies a function to all elements of an array and returns a new array.
  • array_reduce()
    Processes array elements cumulatively and returns a single value.
  • array_walk()
    Executes a function on each element of an array and can modify the array contents directly.

Example

$array = [1, 2, 3, 4];

// array_map: Double each element
$doubled = array_map(function($v) { return $v * 2; }, $array);
print_r($doubled); // [2, 4, 6, 8]

// array_reduce: Calculate the sum of the array
$sum = array_reduce($array, function($carry, $item) {
    return $carry + $item;
}, 0);
echo $sum; // 10

// array_walk: Modify array values directly (by reference)
array_walk($array, function(&$v) { $v += 10; });
print_r($array); // [11, 12, 13, 14]