views:

922

answers:

5

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.

+4  A: 

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.

Ben
the last 4 lines of code can be replaced by array_walk($arr, count);
Paolo Bergantino
+3  A: 

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});
}
TravisO
Yup, the data organisation in the original example is very poor. A solution would be far more viable, and efficient, if the data were organised into an array.
James Burgess
A: 

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, ...).

le dorfier
The OP's code is poor, I've seen many people code this way, it's never a good idea when you have a large set of similar data.
TravisO
So how does your solution make it better? It just makes it more complex. I wouldn't say "4 or 5" is a large set of similar data.
le dorfier
A: 

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

$arr = Array($a, $b, $c, $d);
array_walk($arr, count);
Tom Ritter
array_walk cant be used with most functions. You need array_map.
OIS
A: 

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";
OIS