-2

Current code --

<?php
$arrunsort = array('ab','ad','ar','cd','cb','sc','si','wa','za');
$prevLabel = array();
$currLabelarr = array();
foreach( $arrunsort as $sortelem )
{
    $currLabel = substr($sortelem, 0, 1);
    if( $currLabel !== $prevLabel )
    {
        $currLabelarr[] = $currLabel;
        $prevLabel[] = $currLabel;
    }
}
echo "<pre>";
print_r($currLabelarr);

Output-

Array
(
    [0] => a
    [1] => a
    [2] => a
    [3] => c
    [4] => c
    [5] => s
    [6] => s
    [7] => w
    [8] => z
)

My expected output from the code -

Array
(
    [0] => a
    [1] => c
    [2] => s
    [3] => w
    [4] => z
)

I know I can use array_unique() with this array, but how do I manage it from the above code as output from array_unique looks not too good.

output from print_r(array_unique($currLabelarr));

Array
(
    [0] => a
    [3] => c
    [5] => s
    [7] => w
    [8] => z
)
Trialcoder
  • 5,392
  • 9
  • 40
  • 65
  • 1
    Note alerady that $prevLabel shouldn't be an array... – Laurent S. Jun 27 '13 at 11:30
  • use `array_values(array_unique($currLabelarr))` – Prabhuram Jun 27 '13 at 11:31
  • You have been told that *before* asking a question you should to some research which includes searching this website for the existing information. Please take a bit more care. Also please reduce your code example to a minimum demonstration one that shows the concrete issues. That will also help you to better search for existing material and to better formulate about your problem. – hakre Jun 27 '13 at 11:33
  • @hakre I already flag it to delete this post – Trialcoder Jun 27 '13 at 11:39

3 Answers3

2

Use array_values

print_r(array_values(array_unique($currLabelarr)));

Output

Array
(
[0] => a
[1] => c
[2] => s
[3] => w
[4] => z
)
Yogesh Suthar
  • 30,136
  • 18
  • 69
  • 98
0

Simple

print_r(array_unique($currLabelarr));

You can apply array_values to print the value based unique array

print_r(array_values(array_unique($currLabelarr)));
Gautam3164
  • 28,027
  • 10
  • 58
  • 83
0

Just Change --

$prevLabel[] = $currLabel;

To

$prevLabel = $currLabel;

output -

Array
(
    [0] => a
    [1] => c
    [2] => s
    [3] => w
    [4] => z
)
Trialcoder
  • 5,392
  • 9
  • 40
  • 65