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?
I think you can try this:
$tempArr = $secondArr = array();
foreach($firstArr as $value) {
if(in_array($value,$tempArr)) {
$secondArr[] = $value;
}
$tempArr[] = $value;
}
Hope this will help you out, here we are using array_count_values function for counting the values of an array.
<?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);
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!