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
.
foreach
is simply better. You don't need count and you're dealing with the actual keys of the array.array_search
is far better at iterating than the most optimized PHP code.Example:
foreach( $tags as $tag )
{
while( ( $key = array_search( $tag, $str ) ) !== FALSE )
{
unset( $str[ $key ] );
}
}