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 开发者_如何学Goto check that cycle-counter is in string.
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
}
}
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
}
}
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);
精彩评论