简体   繁体   中英

PHP foreach loop to do something once instead of multiple times

I'm running a foreach loop for the whole script that checks 9 things.

Let's say five of them have value "a" and four of them have value "b".

How do I write an IF condition (or something) that only returns "a" and "b" once?

Simple method (check last value)

Use a variable which stores the previous contents, and compare it with the current iteration (only works if the similar items are sequential)

$last_thing = NULL;
foreach ($things as $thing) {
  // Only do it if the current thing is not the same as the last thing...
  if ($thing != $last_thing) {
    // do the thing
  }
  // Store the current thing for the next loop
  $last_thing = $thing;
}

More robust method (store used values on an array)

Or, if you have complex objects, where you need to check an inner property and the like things are not sequential, store the ones used onto an array:

$used = array();
foreach ($things as $thing) {
  // Check if it has already been used (exists in the $used array)
  if (!in_array($thing, $used)) {
    // do the thing
    // and add it to the $used array
    $used[] = $thing;
  }
}

For example (1):

// Like objects are non-sequential
$things = array('a','a','a','b','b');

$last_thing = NULL;
foreach ($things as $thing) {
  if ($thing != $last_thing) {
    echo $thing . "\n";
  }
  $last_thing = $thing;
}

// Outputs
a
b

For example (2)

$things = array('a','b','b','b','a');
$used = array();
foreach ($things as $thing) {
  if (!in_array($thing, $used)) {
    echo $thing . "\n";
    $used[] = $thing;
  }
}

// Outputs
a
b

Could you be more concrete (it might be helpful to insert a code-snippet with your "content"-objects).

It sounds like, you are trying to get unique values of an array:

$values = array(1,2,2,2,2,4,6,8);
print_r(array_unique($values));
>> array(1,2,4,6,8)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM