2
\$\begingroup\$

Is it possible to declare multiple arrays in PHP in one line?

$userAnswers  = array();
$questionIDs = array ();
$sqlAnswers = array();
$sqlAnswersQuery = array();
$correctAnswers = array();

Any cleaner ways of doing this?

NOTE: The contents of these arrays are all DIFFERENT. I don't think setting them equal to each other would work.

\$\endgroup\$

2 Answers 2

4
\$\begingroup\$

There is a way. Wether you like it or not is another question:

$userAnswers = $questionIDs = $sqlAnswers = $sqlAnswersQuery = $correctAnswers = array();

I'm not a fan of this. This isn't easy to read, especially for the-new-guy-who-doesn't-know-this-code. This works for small amounts of variables, but even then with caution:

$hasErrors = $hasWarnings = false;

I think the way you should declare the variables as array depends on how you set the first values, we can't see enough code to answer based on that.

\$\endgroup\$
2
  • \$\begingroup\$ All of my arrays are going to have different contents, would setting them equal to each other make them have all the same contents? \$\endgroup\$ Jun 22, 2015 at 7:44
  • 1
    \$\begingroup\$ Nope, it's not by reference, you just all set them to the last value of the line. But again, your current method is a better plan. Just add a few spaces to line up the equation signs, will be enough. \$\endgroup\$
    – Martijn
    Jun 22, 2015 at 8:19
3
\$\begingroup\$

This is good as it is. It's recommended to have one statement per line, for better readability: code is easier to read when the logic flows from top to bottom, with no distractions sideways. So even if there was a way to do this on one line, you really shouldn't.

\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.