Max Frai
Max Frai

Reputation: 64336

Trouble with arrays

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.

Upvotes: 0

Views: 80

Answers (3)

Gumbo
Gumbo

Reputation: 655509

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
    }
}

Upvotes: 2

tplaner
tplaner

Reputation: 8461

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);

Upvotes: 1

bschaeffer
bschaeffer

Reputation: 2904

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
    }
}

Upvotes: 5

Related Questions