1

I'm getting an error when using a variable reference. Am I missing something obvious?

basically...

$required = array();
$optional = array();

foreach($things as $thing){
  $list =& $thing->required ? $required : $optional;
  $list[] = $thing;
}

(looping thru list of things, if the thing's required property is true, pass that thing to the list of required things, other pass it to the list of optional things...)

tyia

2
  • @ultimatebuster - 500 Internal Server Error - nothing else is specified Commented Jun 19, 2011 at 17:53
  • You should use your server log Commented Jun 19, 2011 at 20:16

1 Answer 1

1

From the looks of it, it seems like you're trying to separate things that are required or optional into different arrays.

<?php

foreach ( $things as $thing )
{
  if ( $thing->required )
    $required[] = $thing;
  else
    $optional[] = $thing;
}

If you insist on doing it on a single line, you could do this:

<?php

foreach ( $things as $thing )
  ${$thing->required ? 'required' : 'optional'}[] = $thing;

The problem with your code is $list =& $thing->required ? $required : $optional;. PHP is ignoring the ? $required : $optional part is assigning $this->required to $list. When you try to add to the array on the following it, $list is a scalar and no longer an array so it's failing. The only way that I can think to solve that problem is to go with one of the solutions above or to create function that return the array by reference.

Reference: From http://php.net/manual/en/language.operators.comparison.php:

Please note that the ternary operator is a statement, and that it doesn't evaluate to a variable, but to the result of a statement. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions.

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

2 Comments

yes, that works and is what i'm using while trying to figure out why the reference is failing - any idea why saving the array to a reference fails?
@Big MoMo - You can't do what you're doing. I'll add it to my answer.

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.