Bazinga777
Bazinga777

Reputation: 5281

Getting only certain values from an array

I have an array with the following values

    array (size=7)
  0 => string '020120140759' (length=12)
  1 => string '020120140759' (length=12)
  2 => string '020120140759' (length=12)
  3 => string '020220140759' (length=12)
  4 => string '020220140759' (length=12)
  5 => string '020320140759' (length=12)
  6 => string '020320140759' (length=12)

You will notice that the value of certain numbers are the same, I want to extract the last value of each kind that occurs in the array so that a new array will look something likes this.

array (size=2)

  2 (this will change to 0 ) => string '020120140759' (length=12)
  6 (this will change to 1 ) => string '020320140759' (length=12)

I have tried quite a couple of things but i haven't been successful . Any help would be really appreciated

Upvotes: 1

Views: 69

Answers (3)

Liuqing Hu
Liuqing Hu

Reputation: 1980

<?

//first step : Exchanges all keys with their associated values in an array $newArray
//second step: get $newArray's key
[array_flip][1]
[array_keys][2]

$array = array(
  0 =>  '020120140759' ,
  1 =>  '020120140759' ,
  2 =>  '020120140759' ,
  3 =>  '020220140759' ,
  4 =>  '020220140759' ,
  5 =>  '020320140759' ,
  6 =>  '020320140759' 
 );

$newArray = array_keys( array_flip($array) );
echo '<pre>';  
var_dump($newArray);
echo '</pre>';

Upvotes: 0

Shomz
Shomz

Reputation: 37701

array_unique is the way to go.

var_dump( array_unique( array_reverse($yourOriginalArrayHere) ) );

Upvotes: 2

Saddam Abu Ghaida
Saddam Abu Ghaida

Reputation: 6729

you can use array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )

the Sorting flags will be

SORT_REGULAR
SORT_NUMERIC
SORT_STRING
SORT_LOCALE_STRING

example

$result = array_unique($input);
print_r($result);

Upvotes: 0

Related Questions