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.
You can do this
$ids = array(1, 1, 1, 2, 2, 3, 3);
foreach($ids as $key) {
//Calculate the index to avoid duplication
if(isset(${"arr_$key"})) $c = count(${"arr_$key"}) + 1;
else $c = 0;
${"arr_$key"}[$c] = $key;
}
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
array('1, 1, 1'), array('2, 2'), ...