-1
I would like to know how to order this Array, placing the repeated numbers at the end.
$arr = array(
5,
4,
2,
3,
2,
1
);
sort ($arr);
foreach ($arr as $n => $valor) {
echo "$valor\n";
}
-1
I would like to know how to order this Array, placing the repeated numbers at the end.
$arr = array(
5,
4,
2,
3,
2,
1
);
sort ($arr);
foreach ($arr as $n => $valor) {
echo "$valor\n";
}
1
I did the following, sorted the array and then ordered the number of repetitions, then I checked if the quantity was equal to 1, otherwise it adds at the end, through the "for", it adds and comparing if it is the current array of the repetition:
<?php
$arr = array(
5,
4,
2,
3,
2,
1
);
sort($arr);
$add = array();
$contagem = array_count_values($arr);
//sorts by number of repetitions asort($count);
$add = array();
foreach($contagem as $valor => $qtde) {
$current = $valor;
if($qtde == 1) {
$add[] = $valor;
} else {
//o if aqui é só para adicionar uma vez
if ($valor === $current) {
for($i=0; $i < $qtde; $i++) {
$add[] = $valor;
}
}
}
}
print_r($add);
See the example here. And here with other numbers
0
Why do you want them in the end? Maybe what you are thinking of doing, has some other better logic. Because there are basically two things for you to do with the repeaters: remove, or count. I’m thinking you want to count, correct?
Perhaps it would be better for the array to look like this:
// key é o valor do array original, e o value é a quantidade
$array[1] = 1
$array[2] = 2
$array[3] = 1
$array[4] = 2
And later, if you really need them to stay at the end, you would order the value to be increasing, with Sort.
Sorry not to give an example, but it’s been a while since I’ve programmed in PHP, only Javascript. But I believe that changing the logic will be easier.
Any questions during the creation of the code, if you need help with the logic, send the code I finish for you. But at least start doing it!
Browser other questions tagged array php-7
You are not signed in. Login or sign up in order to post.
Give an example of how you want it to look
– bfavaretto
I would like it to look like this: array(1,3,4,5,2,2).
– Guilherme Andrade
And if the entrance is
5,4,2,1,3,2,1
?– bfavaretto
It wouldn’t matter how many input values she had, it would matter how much she got back. I thought about comparing the values repeated from the array, but I don’t know how to put the values repeated at the end of the array.
– Guilherme Andrade
What I want to know is: the ones that don’t repeat are in what order? And if there’s more than one repeat, what should be the order between them?
– bfavaretto
Now I understand, sorry. All would be in ascending order, but the non-repeated ones should come first in the result. For example: array (1,4,2,2,3,3).
– Guilherme Andrade