Logan Serman
Logan Serman

Reputation: 29880

PHP: Apply a function to multiple variables without using an array

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.

Upvotes: 0

Views: 2785

Answers (5)

OIS
OIS

Reputation: 10033

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

Upvotes: 0

Tom Ritter
Tom Ritter

Reputation: 101360

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

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

Upvotes: 1

dkretz
dkretz

Reputation: 37655

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

Upvotes: -1

TravisO
TravisO

Reputation: 9540

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});
}

Upvotes: 3

Ben
Ben

Reputation: 68588

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.

Upvotes: 4

Related Questions