0

I'm trying to count the number of variables that are set to 'yes' using PHP and then output the count.

So for example, I have the following variables:

$facebook = $params->get('facebook');
$twitter = $params->get('twitter');
$email = $params->get('email');
$pinterest = $params->get('pinterest');
$google = $params->get('google');

and if they're all set to 'yes', then there would be a count of 5, using this method:

<?php
    $social = array('facebook', 'twitter', 'email', 'pinterest', 'google');
    echo count($social); // output 5
?>

However, if some are set to 'no' how can I then count all of the ones which are set to 'yes'?

dashtinejad
  • 6,193
  • 4
  • 28
  • 44
RustyIngles
  • 2,433
  • 4
  • 27
  • 31

4 Answers4

3

Use array_filter then count.

$social = array('facebook', 'twitter', 'email', 'pinterest', 'google');
$count = count(array_filter($social, function($val) use ($params) {
  return $params->get($val) === 'yes';
}));
gef
  • 7,025
  • 4
  • 41
  • 48
xdazz
  • 158,678
  • 38
  • 247
  • 274
0

Better add them to array

$vars['facebook'] = $params->get('facebook');
$vars['twitter'] = $params->get('twitter');
$vars['email'] = $params->get('email');
$vars['pinterest'] = $params->get('pinterest');
$vars['google'] = $params->get('google');

Than loop that array

$count = 0;
foreach ($vars as $var) {
    $count += strtolower($var) == 'yes' ? 1 : 0;
}
Justinas
  • 41,402
  • 5
  • 66
  • 96
0

You can set the variables of the various social true if they are equal to 'yes', false otherwise, then just sum them.

$facebook  = ( $params->get('Facebook')  == 'yes');
$twitter   = ( $params->get('twitter')   == 'yes');
$email     = ( $params->get('email')     == 'yes');
$pinterest = ( $params->get('pinterest') == 'yes');
$google    = ( $params->get('google')    == 'yes');

$count = $facebook + $twitter + $email + $pinterest + $google;

Or, if you want to use an array, set the var as before and then you can look at this answer: PHP Count Number of True Values in a Boolean Array

Community
  • 1
  • 1
Sylter
  • 1,622
  • 13
  • 26
0

Well a simple method would be to do a loop and then check each of the values...

$true = 0; //The count...
foreach ($social as $value) {
    if ($value = "yes") { $true++; } //Checks each value if 'yes', increases count...
}
echo $true; //Shows the count...
Kolors
  • 717
  • 1
  • 7
  • 23