Lars
Lars

Reputation: 85

PHP array remove by value inside array

There is an array of airports that gets filled with a user list.

    $airport_array[$airport_row['airportICAO']]    = array(
        'airportName' => $airport_row['airportName'],
        'airportCity' => $airport_row['airportCity'],
        'airportLat' => $airport_row['airportLat'],
        'airportLong' => $airport_row['airportLong'],
        'airportUserCount' => 0,
        'airportUserList' => array()
    );

After filling, "airportUserCount" will either be 0 or higher than 1. Now, I want to remove all airports from the array where airportUserCount is set to 0. What is the most performant way to do it? I thought about a foreach loop but I fear it's not necessarily the most elegant solution.

Upvotes: 1

Views: 79

Answers (5)

Ivan
Ivan

Reputation: 40678

foreach loop, check for the ones that have the Count == 0 then remove them from the array.

$result = array();

foreach ($airport_array[$airport_row['airportICAO']] as $arrays)
{
    if($arrays['airportUserCount'] == 0) {
        array_push($result, $arrays);
    }

}

Upvotes: 2

scottevans93
scottevans93

Reputation: 1079

array_filter allows you to iterate through an array while using a callback function to check values.

function filterAirports($airports){
    return ($airport['airportUserCount'] == 0) ? true : false ;
}

print_r(array_filter($airport_array, "filterAirports"));

Upvotes: 1

jitendrapurohit
jitendrapurohit

Reputation: 9675

Use array_filter:

$a = array_filter($a, function($v) { return $v['airportUserCount'] != 0; });

Demo :- https://eval.in/608464

Upvotes: 1

u_mulder
u_mulder

Reputation: 54841

$new_airports = array_filter(
    $old_airports,
    function($a) { return 0 < $a['airportUserCount']; }
);

Upvotes: 2

Drone
Drone

Reputation: 1134

Use this code

 foreach($airport_array as $key=>$value){
      if($value['airportUserCount']==0){
      unset($airport_array[$key]);
      }
 }

Here is live demo : https://eval.in/608462

Upvotes: 2

Related Questions