I was writing one code, when suddenly I’ve found out, that some strange values appear.
function purify($output){
$temp = 0;
$max_index = count($output);
for($i=0;$i < $max_index; $i++){
if(strlen($output[$i]) == 3){
$str = str_split($output[$i]);
arsort($str);
$str = implode($str);
$output[$temp] = $str;
$temp++;
}
else unset($output[$i]);
}
return array_unique($output);
}
When I pass an array consisting from these elements:
11 115 165 138 999 885 999 456 135 726 642 425 426
I get this output:
array(11) { [1]=> string(3) "651" [2]=> string(3) "831" [3]=> string(3) "999" [4]=> string(3) "885" [6]=> string(3) "654" [7]=> string(3) "531" [8]=> string(3) "762" [9]=> string(3) "642" [10]=> string(3) "542" [12]=> string(3) "426" [0]=> string(3) "511" }
How did the 12th element ([12]=> string(3) “426”) get there when $temp only went up to 11? I can’t get my head around it.
It’s not a good practice to change the array
$outputas you are iterating through it.Consider creating a new array called
$resultand change this line:to:
This way you won’t touch
$outputuntil the end of the loop.It seems to me that you are seeing weird indexes because your changes of
$outputinfluence the next iterations.