1

I have an array:

array:3 [▼
  0 => 1
  1 => 1
  2 => 2
]

I want to count how many times a number is equal in the array and if the count of equal numbers is 2 push the value into an other array.

so:

in this case 1 is equal 2 times, so i want to push 1 into an array.

How do i achieve this?

1

4 Answers 4

1

Hope this will help you out, here we are using array_count_values function for counting the values of an array.

Try this code snippet here

<?php
ini_set('display_errors', 1);
$array=array(
    1,
    1,
    2
);
$result=array();
foreach(array_count_values($array) as $key => $value)
{
    if($value==2)//checking whether the count of number is equal to 2
    {
        $result[]=$key;//pushing value in array
    }
}
print_r($result);
Sign up to request clarification or add additional context in comments.

1 Comment

This helped me, i will approve your answer when i can. Thanks.
1

I think you can try this:

$tempArr = $secondArr = array();
foreach($firstArr as $value) {
   if(in_array($value,$tempArr)) {
       $secondArr[] = $value;
   }
   $tempArr[] = $value;
}

Comments

1

Here you go!

function getMyArray($input_arr, $threshold){
    $final_arr = [];
    $arr_counts = array_count_values($input_arr);
    foreach( $arr_counts as $key => $value ){
        if ( $value == $threshold ){
            $final_arr[] = $key;
        }
    }
    return $final_arr;
}

Pass your input array and your cutoff mark!

Comments

1

-Here is the simplest Solution.

$new_array = array();
$exist_array = array(1,1,2);
  foreach(array_count_values($exist_array) as $k=>$v){
    if($v == 2)
      $new_array[] = $k;
   }

  print_r($new_array);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.