0

I have the following (simplified) code-fragment where I want to assign a value to variable $shell or $hole, depending on a certain condition ($ringIndex===1)

foreach($rings as $ringIndex=>$ring) { $polygon = $this->getPolygonFromRing($ring); if($ringIndex===1) { $shell = $polygon; } else { $hole = $polygon; } .... } 

I don't want to use an extra variable ($polygon) if it is not necessary

I thought maybe something like this would work:

foreach($rings as $ringIndex=>$ring) { ($ringIndex===1?$shell:$hole) = $this>getPolygonFromRing($ring); ... } 
0

2 Answers 2

3

You can use a variable variable.

foreach($rings as $ringIndex=>$ring) { ${$ringIndex===1?'shell':'hole'} = $this->getPolygonFromRing($ring); .... } 

However, I'll add my general advice: Any time you find yourself needing variable variables, you should almost always be using an array instead. If the variables are like $foo1, $foo2, etc. then it should be an indexed array, but in your case it should probably be an associative array with keys shell and hole.

Sign up to request clarification or add additional context in comments.

3 Comments

And I thought mine was naughty.
I originally came up with yours, then realized it could be combined like this.
Brilliant (but potentially dangerous) shortcut and also great advice in the edit.
0
foreach($rings as $ringIndex => $ring){ $var = $ringIndex === 1 ? 'shell' : 'hole'; $$var = $this->getPolygonFromRing($ring); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.