如果我在PHP中定义一个数组,如(我没有定义它的大小):
$cart = array();
我只是简单地添加元素到它使用下面?
$cart[] = 13;
$cart[] = "foo";
$cart[] = obj;
PHP中的数组不是有一个add方法吗,比如cart.add(13)?
如果我在PHP中定义一个数组,如(我没有定义它的大小):
$cart = array();
我只是简单地添加元素到它使用下面?
$cart[] = 13;
$cart[] = "foo";
$cart[] = obj;
PHP中的数组不是有一个add方法吗,比如cart.add(13)?
当前回答
根据我的经验,当关键字不重要时,哪种解决方案是最好的:
$cart = [];
$cart[] = 13;
$cart[] = "foo";
$cart[] = obj;
其他回答
最好不要使用array_push,只使用您建议的方法。函数只是增加了开销。
//We don't need to define the array, but in many cases it's the best solution.
$cart = array();
//Automatic new integer key higher than the highest
//existing integer key in the array, starts at 0.
$cart[] = 13;
$cart[] = 'text';
//Numeric key
$cart[4] = $object;
//Text key (assoc)
$cart['key'] = 'test';
当一个人想要添加以零为基础的元素索引时,我想这也可以工作:
// adding elements to an array with zero-based index
$matrix= array();
$matrix[count($matrix)]= 'element 1';
$matrix[count($matrix)]= 'element 2';
...
$matrix[count($matrix)]= 'element N';
根据我的经验,当关键字不重要时,哪种解决方案是最好的:
$cart = [];
$cart[] = 13;
$cart[] = "foo";
$cart[] = obj;
$cart = array();
$cart[] = 11;
$cart[] = 15;
// etc
//Above is correct. but below one is for further understanding
$cart = array();
for($i = 0; $i <= 5; $i++){
$cart[] = $i;
//if you write $cart = [$i]; you will only take last $i value as first element in array.
}
echo "<pre>";
print_r($cart);
echo "</pre>";
$products_arr["passenger_details"]=array();
array_push($products_arr["passenger_details"],array("Name"=>"Isuru Eshan","E-Mail"=>"isuru.eshan@gmail.com"));
echo "<pre>";
echo json_encode($products_arr,JSON_PRETTY_PRINT);
echo "</pre>";
//OR
$countries = array();
$countries["DK"] = array("code"=>"DK","name"=>"Denmark","d_code"=>"+45");
$countries["DJ"] = array("code"=>"DJ","name"=>"Djibouti","d_code"=>"+253");
$countries["DM"] = array("code"=>"DM","name"=>"Dominica","d_code"=>"+1");
foreach ($countries as $country){
echo "<pre>";
echo print_r($country);
echo "</pre>";
}