PROGRAMMING

 
REMEMBERS




Last update:   29-10-2021

Sort

 
$arr = array('da', 'b', 'c');
sort($arr);
print_r($arr); // [ b, c, da ]

natsort()

Sort an array using a "natural order" algorithm
 
$arr = array('10t', '2t', '3t');
natsort($arr); 
print_r($arr); // [1] => 2t [2] => 3t [0] => 10t
natcasesort - case insensitive
 
$arr = array('10t', '2T', '2t', '3t');
natsort($arr); 
print_r($arr); // [ 2T, 2t, 3t, 10t ]
natcasesort($arr); 
print_r($arr); // [ 2t, 2T, 3t, 10t ]

Usort

Sort an array by values using a user-defined comparison function.
 
$arr = array('three', '2two', 'one', 'two');

function myCmp($left, $right) {

    // sort according to the length of each element.
    if ($diff = strlen($left) - strlen($right)) {
        return $diff;
    }

    // Elements whose values have the same length
    // are further sorted using regular string comparison.

    return strcmp($left, $right);
}

usort($arr, 'myCmp'); 

print_r($arr); //  [one, two, 2two, three]
... 7 lines
 
Filter    (2/3)

Filter

array_filter()

Filters elements of an array using a callback function.
 

$arr = [1, 2, 3, 4, 5, 6];

function odd($var)
{
    return ($var & 1); // integer is odd
}

function even($var)
{
    return (! ($var & 1) ); // not odd
}

print_r(array_filter($arr, 'odd')); //  [1, 3. 5]
print_r(array_filter($arr, 'even'));// [2, 4, 6]
... 6 lines
 

Without callback

Will return only non emtpy values.
 
$arr = array(0=>'a', 1=> false, 2=> null, 3=> 'b');
$arr = array_filter($arr); 

print_r($arr); // [ a, b ]
Multisort    (3/3)

Multisort

array_multisort()

Sort multiple or multi-dimensional arrays
 
$arr1 = array(3,2,1);
$arr2 = array(4,8,0);

array_multisort($arr1, $arr2);

print_r($arr1); // [ 1, 2, 3 ]
print_r($arr2); // [ 0, 8, 4 ]
 
$arr = array(
    array("10", 11, 100, 100, "a"),
    array(1, 2, "2", 3, 1),
);

array_multisort(
    $arr[0], SORT_ASC, SORT_STRING,
    $arr[1], SORT_DESC, SORT_NUMERIC);

var_dump($arr);

// ["10", 100, 100, 11, "a"]
// [ 1, 3, "2", 2, 1 ]
... 5 lines
 

Questions    
Array stacks

        A B C D E F
🔔
1/2