0

I dont know why people declare array before loops and etc..:

$new= array();      // <----- why this is needed ?
foreach($something as $v){
    $new[] = $v;
}

Why to declare the array before setting its value? (In other languages, i.e. C# and JAVA it is needed, but why in PHP?)

3
  • Technically it is not needed, but good practice. Because if the array already exists you just add new values to it, so by assigning an empty array you make sure that the array is empty. Commented Mar 5, 2017 at 18:58
  • See php.net/manual/en/language.types.array.php, and the Creating/modifying with square bracket syntax section. It is always better to initialize a variable by a direct assignment. Commented Mar 5, 2017 at 19:04
  • @Chris85, that's why I've asked... "it's better", but why? @ Rizier, thanks, it's good argument. Commented Mar 6, 2017 at 6:47

1 Answer 1

1

You're not setting its value, you're pushing a new element onto the array. But there needs to be an empty array to push onto.

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

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.