how to check if a name exist multiple times in an array

Viewed 349

i need to check if there is the name john more than 3 times in the names key within the following array that contains 4 different sub arrays

Array
(
    [0] => Array
        (
            [total] => 4.2
            [name] => john
        )

    [1] => Array
        (
            [total] => 2
            [name] => john
        )

    [2] => Array
        (
            [total] => 3
            [name] => adam
        )

    [3] => Array
        (
            [total] => 1.5
            [name] => john
        )

)

i was using mysql first but i prefer to use php instead

3 Answers

You can do the following:

 $counts = array_count_values(array_column($array,"name"));

Then to check if there's 3 people called "john" :

 if (isset($counts["john"]) && $counts["john"] >= 3) {
      //Do stuff
 } else {
      //Do different stuff
  }

To find check all peole not called "john" you can either change the above to as @Andreas suggests:

  if (isset($counts["john"]) && (count($array) - $counts["john"]) > 3) {
     //Do stuff
 } else {
      //Do different stuff
  }

Alternatively do:

 $notJohn = count(array_filter($array, function ($element) {
      return $element["name" != "john";
 }));
 if ($notJohn >= 3) ...

Here, $namesArray in an array with repeated value in it.Target is to count how many time exist each value in array.

$namesArray = array("John","Mark","John","Dan","Hasib","Milon","Samad","Milon","John");

$newArray = array();
    foreach($namesArray as $name){
        if(isset($newArray[$name])){
           $newArray[$name]++;
        }else{
           $newArray[$name] = 1;
        }
    }

According to code here is output :

Array(
  [John] => 3
  [Mark] => 1
  [Dan] => 1
  [Hasib] => 1
  [Milon] => 2
  [Samad] => 1
)

A function like this will do the work I have roughly written it in mobile.

  $occurence = 0;
  function a() {
  for($x = 0; $x < 4; $x++) {
    for($y = 0; $y < 2; $y++) {
      if (array[$x][$y] === "John") {
        $occurence++;
      }
    }
  }
  if($occurence > 3) {
    return false;
  }
  else {
    return true;
    }
 }
Related