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?

3
  • 2
    its hard to get what your expected output is. can you give a code example? Commented Jun 11, 2013 at 8:54
  • [link]stackoverflow.com/questions/16372292/… Already answered here. Commented Jun 11, 2013 at 8:54
  • 2
    Do you want three arrays of one string? Like: array('1, 1, 1'), array('2, 2'), ... Commented Jun 11, 2013 at 8:59

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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
        )

)

Comments

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.