Mann
Mann

Reputation: 606

How to start a foreach loop with a specific value in PHP?

I need to start a for each loop at certain value, ex foreach($somedata as $data) Here I want to start doing some stuff only when the value of that data is "something"

I want to start doing something only after a specific value.

foreach($somedata as $data){
  if($data == 'Something'){
  //start processing, ignore all the before elements.
  }
}

I tried break continue nothing seems to work as I wanted

Upvotes: 0

Views: 2682

Answers (5)

FAROUK BLALOU
FAROUK BLALOU

Reputation: 728

$skip = true;
foreach($somedata as $data){

  if($data == 'Something'){
    $skip = false;
  }

  if($skip) {
   continue;
  }

  //start processing, ignore all before $skip == false.
}

Upvotes: 1

Sarkouille
Sarkouille

Reputation: 1232

If you want to process the values only from the moment you identify one value, then you can use a flag :

$flag = false;
foreach($somedata as $data){
    if($flag OR $data == 'Something'){
        $flag = true;
        // processing some stuff
    }
}

Once the flag is reset to true, whatever the current value is, the content of your if will be executed.

Upvotes: 0

iainn
iainn

Reputation: 17436

For clarity, it's probably better to pre-process your array before looping over it. That way the logic inside your loop can purely focus on what it's supposed to do.

$arr = ['foo', 'something', 'bar'];

$toProcess = array_slice($arr, array_search('something', $arr));

foreach ($toProcess as $element) {
    echo $element, PHP_EOL;
}

outputs

something
bar

Upvotes: 6

Anthony Rivas
Anthony Rivas

Reputation: 962

How about using a indicator variable to achieve this.

$starter = 0;
foreach($somedata as $data){
  if($data == 'Something'){
    $starter = 1;
  }
  if(starter == 1){
    //start processing, ignore all the before elements.
  }
}

Upvotes: 2

deceze
deceze

Reputation: 522372

You'll need to keep a flag whether you have already encountered the desired value or not:

$skip = true;

foreach (... as $data) {
    if ($data == 'something') {
        $skip = false;
    }

    if ($skip) {
        continue;
    }

    // do something
}

Upvotes: 1

Related Questions