tags:

views:

53

answers:

3

Hi guys, I have such string in PHP:

$data = '1;3;5;7;9';

And cycle:

for ($i=0; $i < count($someArray); $i++)
{
   // If $i == any number in $data
}

What is the faster way to compare $i from cycle with numbers in string. I have to check that cycle-counter is in string.

+5  A: 

Just explode the $data into it's own array

$data = '1;3;5;7;9';

$numbers = explode(";", $data);

for($i=0; $i < count($someArray); $i++)
{
    if(in_array($i, $numbers))
    {
        // do something
    }
}
bschaeffer
+1  A: 

You could take this a step further if you are just looking for the values (no further logic within the loop).

$data = '1;3;5;7;9';
$numbers = explode(";", $data);

$result = array_intersect($numbers, range(0, count($someArray)));

print_r($result);
evolve
+2  A: 

I would use the numbers as keys for an index:

$data = '1;3;5;7;9';
$index = array_flip(explode(';', $data));

Now you can simply use isset or array_key_exists to check if that number is in $data:

for ($i=0, $n=count($someArray); $i<$n; ++$i) {
   if (array_key_exists($index, $i)) {
       // $i is in $data
   }
}

You can even do the reverse, iterate the numbers in $data and see if they are in the range from 0 to count($someArray)-1:

$data = '1;3;5;7;9';
$n = count($someArray);
foreach (explode(';', $data) as $number) {
    if (0 <= $number && $number < $n) {
        // $number is in range from 0 to $n-1
    }
}
Gumbo
Is `array_key_exists` more reliable than `in_array`?
bschaeffer
@bschaeffer: It’s more efficient: `isset` and `array_key_exists` should be O(1) while `in_array` is O(n).
Gumbo