1

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?

HamZa
  • 14,051
  • 11
  • 52
  • 72
Joshua Fabillar
  • 496
  • 2
  • 9
  • 24
  • 2
    its hard to get what your expected output is. can you give a code example? – hek2mgl Jun 11 '13 at 08:54
  • [link]http://stackoverflow.com/questions/16372292/how-to-delete-duplicates-in-an-array[/link] Already answered here. – Ali Jun 11 '13 at 08:54
  • 2
    Do you want three arrays of one string? Like: `array('1, 1, 1'), array('2, 2'), ...` – Lebugg Jun 11 '13 at 08:59

4 Answers4

5

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.

Joel Hinz
  • 23,685
  • 6
  • 57
  • 74
4

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
        )

)
HamZa
  • 14,051
  • 11
  • 52
  • 72
3

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;
}

Demo

Starx
  • 75,098
  • 44
  • 181
  • 258
2

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