I am trying to figure out how to use loops with count tag on php for the first time. It will be highly appreciated if you could point me in the right direction
$people = [
['name' => 'Allan', 'gender' => 'male'],
['name' => 'Rhea', 'gender' => 'female'],
['name' => 'Jane', 'gender' => 'female'],
];
$counterMale = 0;
//insert loop to count the "male"
//insert loop to count the 'female'
echo "Male count is $counterMale";
CodePudding user response:
Wanted to post it as comment but looks like i can't comment because i don't have enough reputations, so posting it as answer.
You just have to iterate over $people
array and then for each array you have to check whether array["gender"]
is male
or female
and increase the respective counter.
Here is the code snippet:
$people = [
['name' => 'Allan', 'gender' => 'male'],
['name' => 'Rhea', 'gender' => 'female'],
['name' => 'Jane', 'gender' => 'female'],
];
$counterMale = 0;
$counterFemale = 0;
foreach($people as $p)
{
if($p['gender'] == "male")
{
$counterMale;
}
else if($p['gender'] == "female")
{
$counterFemale;
}
}
echo "Male count is ". $counterMale.PHP_EOL;
echo "Female count is ". $counterFemale;
CodePudding user response:
$people = [
['name' => 'Allan', 'gender' => 'male'],
['name' => 'Rhea', 'gender' => 'female'],
['name' => 'Jane', 'gender' => 'female'],
];
echo array_count_values(array_column($people, 'gender'))['male'];
// male count with case sensitive
// without single value throw error
For more details refer this