June 11, 2013

Php array duplicates separation

Joshua Fabillar’s Question:

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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!