1

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.

1
  • use array_filter Commented Jul 20, 2016 at 9:01

5 Answers 5

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks to all of you :)
2
$new_airports = array_filter(
    $old_airports,
    function($a) { return 0 < $a['airportUserCount']; }
);

2 Comments

Thanks to all of you :)
Can be simply {return $v['airportUserCount'];})
2

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);
    }

}

1 Comment

Thanks to all of you :)
1

Use array_filter:

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

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

Comments

1

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"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.