Skip to content
Advertisement

Sort an array so that a given value would be the first

I would like to sort the array so that if a given value ($first_in_array) = 'brand' value, the array would become the first it the queue. In the given example an array with index[1] should appear like at index[0].

$first_in_array = 'PickMeFirst';

$data = Array(
    0 => array(
        'articleId'     => 5478,
        'articleName'   => 'Demo artcle name 1',
        'brand'         => 'Unbranded',
       ),
    1 => array(
        'articleId'     => 8785,
        'articleName'   => 'Demo artcle name 2',
        'brand'         => 'PickMeFirst',
       ),
    2 => array(
        'articleId'     => 1258,
        'articleName'   => 'Demo artcle name 3',
        'brand'         => 'None',
       ),
); 

Advertisement

Answer

You can use the callback function of usort and first deal with the case where exactly one of the two matches that specific string. In all other cases use the normal strcmp result:

usort($data, function ($a, $b) use ($first_in_array)  {
    return ($b["brand"] === $first_in_array) - ($a["brand"] === $first_in_array)
        ?: strcmp($a["brand"], $b["brand"]);
});
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement