1

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?

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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)

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.