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
Php: Get the Key from an Array in a Foreach Loop
JSON_Encode Function: Special Characters
Accessing Class Properties with Spaces
Using X-Sendfile with Apache/Php
How to Access an Object Attribute That Starts with a Number
Display the Discounted Percentage Near Sale Price in Single Product Pages for Wc 3.0+
Bcrypt and Randomly Generated Salts
Call to a Member Function Fetch() on Boolean
Doctrine Query Language Get Max/Latest Row Per Group
The Post Method Is Not Supported for This Route. Supported Methods: Get, Head. Laravel
Strip All HTML Tags, Except Allowed
How to Get Rid of MySQL Error 'Prepared Statement Needs to Be Re-Prepared'
Least Memory Intensive Way to Read a File in PHP
PHP Configuration: It Is Not Safe to Rely on the System's Timezone Settings
How to Replace (Monkeypatch) PHP Functions
How to Tell If a File Is Text Using PHP
Mysql_Num_Rows(): Supplied Argument Is Not a Valid MySQL Result Resource