1

Basic question really, I know I can do this in some other languages but I dont know PHP that well, hoping someone can help.

So I have the following.

$holyToT *=100;
$coldToT *=100;
$fireToT *=100;
$poisonToT *=100;
$lightningToT *=100;

And I want to be able to just condense it down to something like:

$holyToT, $coldToT, $fireToT, $poisonToT, $lightningToT *= 100;

Does PHP have an internal way of doing something similar?

2
  • 1
    No, it doesn't. You can cascade normal assignments, but not assignments with an operator. Commented May 21, 2014 at 18:18
  • You can write a small snippet code code that reduces the number of lines of code but at the cost of complexity (and possibly maintainability) Commented May 21, 2014 at 18:22

3 Answers 3

2

I agree with the others, but if you really want to have it in one line, you could do something like this:

list($holyToT, $coldToT, $fireToT, $poisonToT, $lightningToT) = array_map(function($x) { return $x*100;}, array($holyToT, $coldToT, $fireToT, $poisonToT, $lightningToT));
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah I was afraid of that. If thats the only other option, I guess i'll stick to the block of code for sets this small.
2

There is no syntax that allows you to do exactly this in a single statement.

You could cook up ways of doing this (by pushing everything inside an array), but the result would be much less clear and performant than a group of assignments.

Something like this comes to mind, but if they catch you doing this don't say you heard it from me:

extract(array_map(
    function($i) { return $i * 100; },
    compact('holyToT', 'coldToT', 'fireToT' /*, ... */ )
));

Comments

1

There is ni build in functionality. Depending on the PHP Version you could pass an array and a lambda function to a custom function.

function performOnAll(array $a, $fct) { 
    foreach($a as $v) $fct(&$a); 
} 

performOnAll(array($a, $b, ...), function(&$a) { $a *= 100; });

That's it basically (not syntax checked).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.