Search code examples
phparray-multisort

PHP array_multisort with some missing keys


In two arrays I'm missing keys ($billing). Is there a way I can ignore, skip or just not take that given array iteration in to consideration and still sort the array?

I get the error message:

array_multisort(): Argument #1 is expected to be an array or a sort flag

foreach ($table as $key => $row)
{
   $billing[$key]  = $row['billing']['date_due'];
}

if ($_GET['billing']=='desc') {array_multisort($billing, SORT_DESC, $table);}
else {array_multisort($billing, SORT_ASC, $table);}

Solution

  • You can just check if a variable/key is set or is not empty:

    <?php
    foreach ($table as $key => $row) {
       $billing[$key]  = isset($row['billing']['date_due']) ? $row['billing']['date_due'] : null;
    }
    
    // $billing doesn't exist, if $table is empty
    if (!empty($billing)) {
      array_multisort($billing, ($_GET['billing']=='desc' ? SORT_DESC : SORT_ASC), $table);
    } else {
      array_multisort($table); // or simply sort($table);
    }
    

    Another way is to initialize $billing before foreach: $billing = [];.