1

I have a foreach loop that iterates through an array but I want to check if the array contains $item == 'survey-east-upper' and if that's true then hide the previous $item which is 'survey-east'. I've looked into in_array but can't figure how to remove the previous element.

My original code:

foreach ($survey_array->Services as $service) {
  foreach ($service as $item) {
    echo '<li title="' . rtrim($item) . '" class="' . strtolower(preg_replace('/[^a-zA-Z0-9]/', '-', rtrim($item))) . '">' . $item . '</li>';
    }
  }

The new code:

foreach ($survey_array->Services as $service) {
  foreach ($service as $item) {
    if (in_array("survey-east-upper", $survey_array->Services)) {
       unset($site->Services['survey-east']);
    }
    echo '<li title="' . rtrim($item) . '" class="' . strtolower(preg_replace('/[^a-zA-Z0-9]/', '-', rtrim($item))) . '">' . $item . '</li>';
    }
  }

How can I accomplish this?

5
  • 1
    One does not simply remove a loop. (Have you tried using a break; to escape the loop)? Commented May 21, 2013 at 16:58
  • What does $site->Services contain? Can you post a dump of its contents? Commented May 21, 2013 at 17:01
  • I will take a look into breaks. So is the wrong way to go about it?stackoverflow.com/questions/2304570/… Commented May 21, 2013 at 17:04
  • I would not recommend to edit array with unset od adding during its iterations... it can create confusing code and weird behaviour. Commented May 21, 2013 at 17:07
  • Sorry George that was mean't to be $survey_array->Services not $site->Services. Not helpful I know but I'll correct the question. stdClass Object ( [SurveyArray] => Array ( [0] => stdClass Object ( [ServiceName] => SurveyEast ) [1] => stdClass Object ( [ServiceName] => SurveyEastUpper ) ) ) Commented May 21, 2013 at 17:09

1 Answer 1

2

Dont use foreach, use for with indexing. In every iteration, look one item ahead and check that item. If its "survey-east-upper", skip actual iteration and continue further.

foreach ($survey_array->Services as $service) {
  for ($i = 0; $i < count($service) - 1; $i++) {
    $item = $service[$i];
    if ($service[$i + 1] == "survey-east-upper") {
         continue;
    }
    echo '<li title="' . rtrim($item) . '" class="' . strtolower(preg_replace('/[^a-zA-Z0-9]/', '-', rtrim($item))) . '">' . $item . '</li>';
    }

  }

Edit:

You have to do something with last item in array $service[count($service) - 1], because that wont be included in for loop

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.