0

Here's the issue:

I retrieve the following data string from my database:

$row->exceptions = '1,2,3';

After explode I need the below code to check each one of the exploded pieces

$exceptions = explode(",", $row->exceptions);

//result is 
//[0] => 1
//[1] => 2
//[2] => 3

for ($i = 0; $i <= $row->frequency; $i++) {

    if ($exceptions[] == $i) {

        continue;

    } else {

        //do something else
    }
}

How can I make $exceptions[] loop through all keys from the exploded array so it evaluates if ==$i?

Thanks for helping.

pepe
  • 9,799
  • 25
  • 110
  • 188
  • possible duplicate of [Find Value in Array](http://stackoverflow.com/questions/4703004/find-value-in-array) – Ignacio Vazquez-Abrams May 08 '11 at 05:34
  • not sure about that - here i am in need of a solution not to find a specific key, but to loop through all keys – pepe May 08 '11 at 05:37
  • 1
    I'm not sure I got your question, so I'm posting a comment: if I got it, it should suffice to substitute "if($exceptions[] == $i)" with "if(in_array($i,$exceptions))". – Paolo Stefan May 08 '11 at 05:50
  • @paolo, that's an elegant solution and works nicely - would you mind posting it as answer? - thanks – pepe May 08 '11 at 05:55

3 Answers3

2

It should suffice to substitute:

if($exceptions[] == $i)

with:

if(in_array($i,$exceptions))

By the way, it eliminates the need for a nested loop.

Paolo Stefan
  • 10,112
  • 5
  • 45
  • 64
1

Ah, should be straightforward, no?

$exceptions = explode(",", $row->exceptions);
for ($i = 0; $i <= $row->frequency; $i++) {

    foreach($exceptions as $j){
    if($j == $i){
        // do something
        break;
    }
}
}
Femi
  • 64,273
  • 8
  • 118
  • 148
  • Glad to help: `in_array` is more elegant. No reason not to use the platform functions if they are available and fit the task. – Femi May 08 '11 at 05:58
0

I think I understand what you are asking. Here's how you would test within that loop whether the key equals $i.

for ($i = 0; $i <= $row->frequency; $i++)
{
  foreach ($exceptions as $key => $value)
  {
    if ($key == $i)
    {
      continue;
    }
  }
}
James Skidmore
  • 49,340
  • 32
  • 108
  • 136