Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an array with duplicated value from an array (PhP)

Tags:

arrays

php

max

I want to create an new array with duplicated MAX value from an array and put other duplicate value in an other array

      $etudiant = array ('a'=>'2','b'=>'5', 'c'=>'6', 'd'=>'6', 'e'=>'2');

and i want this result

     $MaxArray =  array ('c'=>'6', 'd'=>'6');
     $otherarray1 =  array ('a'=>'2', 'e'=>'2');

Thank you !

like image 213
Kevin Houde Avatar asked Jun 03 '11 20:06

Kevin Houde


1 Answers

First, find the maximum value:

$etudiant = array ('a'=>'2','b'=>'5', 'c'=>'6', 'd'=>'6', 'e'=>'2');
$maxValue = max($etudiant);

Second, find values that appear more than once:

$dups = array_diff_assoc($etudiant, array_unique($etudiant));

Lastly, check the original arrays for values matching either $maxValue or values that are listed in $dups:

$MaxArray = $OtherArray = $ElseArray = array();
foreach ($etudiant as $key => $value) {
    if ($value == $maxValue) {
        $MaxArray[$key] = $value;
    } else if (in_array($value, $dups)) {
        $OtherArray[$key] = $value;
    } else {
        $ElseArray[$key] = $value;
    }
}

You'll get:

$MaxArray: Array
(
    [c] => 6
    [d] => 6
)
$OtherArray: Array
(
    [a] => 2
    [e] => 2
)

Note: I wasn't sure if you wanted the $MaxArray to contain the maximum value elements only if it appears more than once in the source array. If so, just change the max call to:

$maxValue = max($dups);
like image 176
netcoder Avatar answered Sep 23 '22 14:09

netcoder