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.

Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jun 22, 2015 at 6:07
\$\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.

answered Jun 22, 2015 at 7:42
\$\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\$ Commented 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\$ Commented 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.

answered Jun 22, 2015 at 6:19
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.