In PHP I have a arrays of id
$ids = array(1, 1, 1, 2, 2, 3, 3);
I just wanted to separate the 1 which will become 1, 1, 1
and 2 become 2, 2
and 3 become 3, 3
.
How can I do that in PHP?
In PHP I have a arrays of id
$ids = array(1, 1, 1, 2, 2, 3, 3);
I just wanted to separate the 1 which will become 1, 1, 1
and 2 become 2, 2
and 3 become 3, 3
.
How can I do that in PHP?
You can use array_count_values to find out how many times each element occurs in the array. You won't have {1, 1, 1}
but you'll have [1] => 3
which I hope amounts to the same thing for your use.
This could easily be done by a simple loop:
$ids = array(1, 1, 1, 2, 2, 3, 3);
foreach($ids as $id){
$new[$id][] = $id;
}
print_r($new);
Output:
Array
(
[1] => Array
(
[0] => 1
[1] => 1
[2] => 1
)
[2] => Array
(
[0] => 2
[1] => 2
)
[3] => Array
(
[0] => 3
[1] => 3
)
)
I understand that you want distinct array values (no repetition). If so, then here goes:
$ids = array(1, 1, 1, 2, 2, 3, 3);
$distinct_ids = array_values(array_unique($ids));
to give the output as
array (size=3)
0 => int 1
1 => int 2
2 => int 3
array_unique
removes duplicate values from the array, while array_value
resets the array keys.
Documentation: array_values
, array_unique