Question

I have a function (for ease, I'll just use count()) that I want to apply to maybe 4-5 different variables. Right now, I am doing this:

$a = count($a);
$b = count($b);
$c = count($c);
$d = count($d);

Is there a better way? I know arrays can use the array_map function, but I want the values to remain as separate values, instead of values inside of an array.

Thanks.

Was it helpful?

Solution

I know you said you don't want the values to be in an array, but how about just creating an array specifically for looping through the values? i.e.:

$arr = Array($a, $b, $c, $d);

foreach ($arr as &$var)
{
   $var = count($var);
}

I'm not sure if that really is much tidier than the original way, though.

OTHER TIPS

If you have a bunch of repeating variables to collect data your code is poorly designed and should just be using an array to store the values, instead of dozens of variables. So perhaps you want something like:

$totals = array("Visa"=>0,"Mastercard"=>0,"Discover"=>0,"AmericanExpress"=>0);

then you simply add to your array element (say from a while loop from your SQL or whatever you are doing)

$totals['Visa'] += $row['total'];

But if you really want to go down this route, you could use the tools given to you, if you want to do this with a large batch then an array is a good choice. Then foreach the array and use variable variables, like so:

$variables = array('a','b','c'...);

foreach ( $variables as $var )
{
    ${$var} = count(${var});
}

What Ben and TravisO said, but use array_walk for a little cleaner code:

$arr = Array($a, $b, $c, $d);
array_walk($arr, count);

You can use extract to get the values back out again.

//test data
$a = range(1, rand(4,9));
$b = range(1, rand(4,9));
$c = range(1, rand(4,9));

//the code
$arr = array('a' => $a, 'b' => $b, 'c' => $c);
$arr = array_map('count', $arr);
extract($arr);

//whats the count now then?
echo "a is $a, b is $b and c is $c.\n";

How do you measure "better"? You might be able to come up with something clever and shorter, but what you have seems like it's easiest to understand, which is job 1. I'd leave it as it is, but assign to new variables (e.g. $sum_a, ...).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top