Gary
Gary

Reputation: 1011

excluding values from a foreach loop

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?

Upvotes: 6

Views: 4384

Answers (4)

mario
mario

Reputation: 145482

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

Upvotes: 4

Nick D
Nick D

Reputation: 589

I'd probably write it a little different this isn't correct ($name isn't an object)

$name->last_name_id

Something along the lines of:

$last_names = regapiGetLastNames( NULL, -1 );
$exclude = array('11196','11195','11198','11197');

foreach ($last_names as $name => $last_name_id) {
    if(!in_array($last_name_id, $exclude)) print '<option value="'.$last_name_id.'">'.$name.'</option>';
}

Upvotes: 0

Kai Qing
Kai Qing

Reputation: 18833

$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

Upvotes: 2

alex
alex

Reputation: 490283

You could turn that into...

$last_names = regapiGetLastNames( NULL, -1 );

$last_names = array_filter($last_names, function($value) {
    return in_array($value, array('11196','11195','11198','11197'));
});

foreach ($last_names as $name => $last_name_id) {
    print '<option value="'.$last_name_id.'">'.$name.'</option>';
}

When you get to doing your loop, you are only iterating over the set you want. This is useful for separating your business rules (dropping certain ids) and presentation (echoing the HTML).

Upvotes: 0

Related Questions