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?

hakre
  • 193,403
  • 52
  • 435
  • 836
ShambalaG
  • 356
  • 1
  • 7
  • 21
  • 1
    One does not simply remove a loop. (Have you tried using a break; to escape the loop)? – Jack M. May 21 '13 at 16:58
  • What does `$site->Services` contain? Can you post a dump of its contents? – George Cummins May 21 '13 at 17:01
  • I will take a look into breaks. So is the wrong way to go about it?http://stackoverflow.com/questions/2304570/how-to-delete-object-from-array-inside-foreach-loop – ShambalaG May 21 '13 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. – Martin Perry May 21 '13 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 ) ) ) ` – ShambalaG May 21 '13 at 17:09

1 Answers1

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

Martin Perry
  • 9,232
  • 8
  • 46
  • 114