minte9
LearnRemember



Sort

Natsort uses a natural order algorithm.
 
/**
 * sort(), natsort()
 */

$A = ['da', 'b', 'c'];
$B = ['10t', '2t', '3t'];

sort($A);
natsort($B); 

print_r($A); // b, c, da
print_r($B); // [1] => 2t [2] => 3t [0] => 10t

Filter

Filters elements of an array using a callback function.
 
declare(strict_types=1);

/**
 * array_filter()
 * 
 * Without a callback returns non empty values
 */

$A = [1, 2, 3, 4, 5, 6];
$B = [1, false, null, 'b'];

function odd($var) : int
{
    return ($var & 1); // bits set in both
}

function isEven($var) : bool
{
    return ! ($var & 1); // bit 1 not set
}

print_r(array_filter($A, 'odd'));    // [1, 3. 5]
print_r(array_filter($A, 'isEven')); // [2, 4, 6]
print_r(array_filter($B));           // [0 => 1, 3 => b]

Multisort

Sort multiple or multi-dimensional arrays
 
/**
 * array_multisort()
 * 
 * Sorting destroys all the keys and rearange elements
 */

$A = [3,2,1];
$B = [4,8,0];

array_multisort($A, $B);

print_r($A); // 1, 2, 3
print_r($B); // 0, 8, 4
 
$C = [
    ["10", 11, 100, 100, "a"],
    [1, 2, "2", 3, 1],
];

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

print_r($C);
    // ["10", 100, 100, 11, "a"]
    // [ 1, 3, "2", 2, 1 ]



  Last update: 213 days ago