If I define an array in PHP such as (I don't define its size):
$cart = array();
Do I simply add elements to it using the following?
$cart[] = 13; $cart[] = "foo"; $cart[] = obj;
Don't arrays in PHP have an add method, for example, cart.add(13)
?
Answer: Use the array_push() Function You can simply use the array_push() function to add new elements or values to an empty PHP array.
Definition and Usage. The array_push() function inserts one or more elements to the end of an array. Tip: You can add one value, or as many as you like. Note: Even if your array has string keys, your added elements will always have numeric keys (See example below).
Syntax to create an empty array:$emptyArray = []; $emptyArray = array(); $emptyArray = (array) null; While push an element to the array it can use $emptyArray[] = “first”. At this time, $emptyArray contains “first”, with this command and sending “first” to the array which is declared empty at starting.
An empty array is falsey in PHP, so you don't even need to use empty() as others have suggested. PHP's empty() determines if a variable doesn't exist or has a falsey value (like array() , 0 , null , false , etc).
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); ?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With