I want to count the recurrence of a true or false and output which has the most. Is there a predefined function to do this in PHP? So far I have done it like this ( isHappy()
method):
class Girl {
private $issues = [];
public function addIssue($details) {
this->issues[] = [$details, false];
return;
}
public function isHappy() {
$true = [];
$false = [];
foreach($this->issues as $issue) {
if($issue[1]) { $true[] = true; } else { $false[] = false; }
}
// what if its == to one another? do we return happy or sad?
return count($true) < count($false) ? false : true;
}
public function resolveIssue() {
for($i = 0; $i <= count($this->issues); $i++) {
if(!$this->issues[$i][1]) {
$this->issues[$i][1] = true;
break;
}
}
return;
}
}
So when I run it, I can get the average of if she is happy or not:
$her = new Girl();
$her->addIssue('Deleted our messages');
$her->addIssue('Over reacted');
$her->addIssue('Told her family to pretty much **** off');
echo $her->isHappy() ? 'it is all ok:)' : 'she hates u, hang urself.';
PS: It should probably return false every time cos you can't win.
You want array_count_values
:
function isHappy(array $issues) {
$happiness = array_count_values(array_map('intval', $issues));
return $happiness[1] > $happiness[0];
}
print_r(
isHappy([ true, false, true, true, false ])
);
Note that array_count_values
only works on string and int, so I'm mapping the given boolean
to int
for processing.
array_sum()
type juggles for you, so simply compare the sum of all true
with all issues minus the true
(which yields all false
):
public function isHappy() {
return ($true = array_sum($this->issues)) > (count($this->issues) - $true);
}
Get the keys where the value is true
and count it, do the same for false
and compare:
return count(array_keys($this->issues, true)) > count(array_keys($this->issues, false));
Or a number of other possible combinations.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.