phparraysfilteringarray-filter

Filter a 2d array to only keep rows where a specific column value is greater than nominated value


I have a form that submits the following data. I only want to select the data with QTY of 1 or more.

array (size=4)
  17 => 
    array (size=4)
      'id' => string '17' (length=2)
      'TicketName' => string 'General admission' (length=17)
      'price' => string '50.00' (length=5)
      'qty' => string '0' (length=1)
  18 => 
    array (size=4)
      'id' => string '18' (length=2)
      'TicketName' => string 'General admission' (length=17)
      'price' => string '50.00' (length=5)
      'qty' => string '2' (length=1)
  19 => 
    array (size=4)
      'id' => string '19' (length=2)
      'TicketName' => string 'General admission' (length=17)
      'price' => string '50.00' (length=5)
      'qty' => string '0' (length=1)
  20 => 
    array (size=4)
      'id' => string '20' (length=2)
      'TicketName' => string 'General admission' (length=17)
      'price' => string '50.00' (length=5)
      'qty' => string '0' (length=1)
    

I know I can use something like. I'm not sure how to filter by the qty key.

$arrays = array_filter($inputs, function($val) {
                return $val > 0;
          });

Solution

  • Each element of your array $input, is an array. So you need to access the value associated to the key qty:

    $arrays = array_filter($inputs, function($elem){
        return (int)$elem['qty'] > 0;
    });