Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

excluding values from a foreach loop

Tags:

foreach

php

I have the following code.. and I know it's probably all wrong, but I haven't dealt with foreach loops before.

$last_names = regapiGetLastNames( NULL, -1 );
foreach ($last_names as $name => $last_name_id)
    $exclude = array('11196','11195','11198','11197');
    if(!in_array($name->last_name_id, $exclude)):
    print '<option value="'.$last_name_id.'">'.$name.'</option>';

Obviously its going wrong somewhere, any help pls?

like image 590
Gary Avatar asked Nov 17 '11 22:11

Gary


2 Answers

If the IDs are array values, then you can also use array_diff to filter them:

$last_names = regapiGetLastNames( NULL, -1 );

$exclude = array('11196','11195','11198','11197');
$last_names = array_diff($last_names, $exclude);

foreach ($last_names as $name => $last_name_id) {
    print '<option value="'.$last_name_id.'">'.$name.'</option>';
}
like image 148
mario Avatar answered Sep 20 '22 23:09

mario


$last_names = regapiGetLastNames( NULL, -1 );
$exclude = array('11196','11195','11198','11197');
foreach ($last_names as $name => $last_name_id)
{
    if(!in_array($name->last_name_id, $exclude))
        print '<option value="'.$last_name_id.'">'.$name.'</option>';
}

You need the braces for a multiline loop. also, move the array declaration outside the loop

like image 45
Kai Qing Avatar answered Sep 18 '22 23:09

Kai Qing