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($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?
Assuming that you’re not using
array_diff.foreachis simply better. You don’t need count and you’re dealing with the actual keys of the array.array_searchis far better at iterating than the most optimized PHP code.Example: