Is It Necessary to Declare PHP Array Before Adding Values with []

Is it necessary to declare PHP array before adding values with []?

If you don't declare a new array, and the data that creates / updates the array fails for any reason, then any future code that tries to use the array will E_FATAL because the array doesn't exist.

For example, foreach() will throw an error if the array was not declared and no values were added to it. However, no errors will occur if the array is simply empty, as would be the case had you declared it.

Should an array be declared before using it?

Best Practice is declaring it.

Reason: if for some reason someone turned on register_globals and $array is set before you use it, you can end up with strange results.
If you declare it, you are always sure you have an empty array.

Is it necessary or useful to initialize sub-arrays in PHP?

It's unnecessary as far as PHP is concerned. PHP will implicitly create any number of sub-arrays for you using the $foo[$bar][] syntax. It may be required for business logic, though not in this particular arrangement; it's simply redundant here. If the value assignment is somehow separate logic, but you still want to ensure that at least an empty array exists for the key, that's the only time it makes sense.

How to add elements to an empty array in PHP?

Both array_push and the method you described will work.

$cart = array();
$cart[] = 13;
$cart[] = 14;
// etc

//Above is correct. but below one is for further understanding
$cart = array();
for($i=0;$i<=5;$i++){
$cart[] = $i;
}
echo "<pre>";
print_r($cart);
echo "</pre>";

Is the same as:

<?php
$cart = array();
array_push($cart, 13);
array_push($cart, 14);

// Or
$cart = array();
array_push($cart, 13, 14);
?>

PHP Array Operator

Better yet, just initialize your array and assign values to it at the same time:

<?php
$array = array(
"a" => "apple",
"b" => "banana"
);
?>


Related Topics



Leave a reply



Submit