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 $output
as you are iterating through it.
Consider creating a new array called $result
and change this line:
$output[$temp] = $str;
to:
$result[$temp] = $str;
This way you won't touch $output
until the end of the loop.
It seems to me that you are seeing weird indexes because your changes of $output
influence the next iterations.
Since you are overwriting the parameter output array, the elements initially in the array remain where they are (except if their length is != 3).
Maybe you could try
function purify($output){
$result = array();
$max_index = count($output);
for($i=0;$i < $max_index; $i++){
if(strlen($output[$i]) == 3){
$str = str_split($output[$i]);
arsort($str);
$result[] = implode($str);
}
}
return array_unique($result);
}
By the way, do you really want to use arsort
and not rsort
? rsort
makes sense since you are using an indexed array (and not an associative array).
rsort($str);