FOR cycle requiring more repeats then it should for a result I need
I've got a problem. In my opinion this should work fine:
for($i = 0; $i < count($tags); $i++){
if(in_array($tags[$i], $str)){
for($a = 0; $a < count($str); $a++){
if($tags[$i] == $str[$a]){
unset($str[$a]);
}
}
}
}
str is an array consisting of 1, 3, 4, 5, 500, 501.
tags is an array consisting of 4, 5, 500, 501.
The result should be 1, 3. The result is 1, 3, 500, 501.
After experimenting, I found out that this code works but is unstable, in my opinion:
for开发者_如何学C($i = 0; $i < count($str) + count($tags); $i++){
for($a = 0; $a < count($tags); $a++){
if ($tags[$a] == $str[$i]) {
unset($str[$i]);
}
}
$a = 0;
}
What am I doing wrong?
Far too much code, when you could simply do:
$difference = array_diff($tags, $str);
Assuming that you're not using array_diff
.
- Unless you have an extremely compelling reason,
foreach
is simply better. You don't need count and you're dealing with the actual keys of the array. - The built in array functions are your friends.
array_search
is far better at iterating than the most optimized PHP code. - While loops can make your life better :-)
Example:
foreach( $tags as $tag )
{
while( ( $key = array_search( $tag, $str ) ) !== FALSE )
{
unset( $str[ $key ] );
}
}
精彩评论