2014-04-01 42 views
3

我特別想知道:在使用它之前,你必須初始化一個php數組嗎?

$thisArray = array (
    'bla' => array (
     '4', '5', '6' 
    ) 
); 

難道我剛纔做這個:

$thisArray['bla'] = array('4', '5', '6'); 

我可以看到它的工作原理,但它認爲是正確的和好的做法呢?

+0

更好的是$ thisArray ['bla'] = ['4','5','6']; – Brovoker

+0

爲什麼這不應該是一個好習慣?一個數組幾乎和其他所有變量一樣隨意使用它;-) – DonCallisto

+0

Imho初始化意味着您首先將類型賦值給具有零/空/假值的變量。你在這裏做的是同一件事情的不同語法。 – Andrew

回答

2

這不是關於「良好做法」。這兩個選項都是有效的(並且不會產生通知)。在第一種情況下,你已經知道了關於陣列中的數據,因此,能夠與array()

明確聲明它但在普通情況下,你就不能申報陣列這樣的方式 - 這可能是動態的 - 它可以有不同的值,它可能有不同的尺寸e tc因此,儘管這兩個選項都是有效的,但第二個選項將用於許多常見的情況,其中數組將保存一些數據,這些數據由應用程序邏輯控制。

多說 - 幾乎在具有陣列中的所有感 - 以保持其根據應用程序架構&邏輯結構的動態數據。

-2
**if i am wrong plz make me correct.** 

    In php you Don't want to initialization variables and array...its totally depends upon you what you do ..... 
But in some cases when the value array and variable equal to null...then 


    **case:1-** When you are not define a variable and you are using that variable in if condition then it will gives you error notice..to make clear from that notice you want to put "@" sign before that 

    **example:-** 

    <?php  
    if($a==5){//here you not initialized variable so it gives you notice... 
    //code to run 
    } 
    ?> 


    **case 2:-** If you playing with array and doing same like not initialized that the it will also gives you notice:- 

    example:- 

    <?php 

    foreach($arr as $arr1){ // here $arr is also not initialized 
    //code to run 
    } 

    ?> 
    help:- To save your self from notice plz initialized them equal to null_for more info follow this... 

    http://php.vrana.cz/variable-initialization-in-php.php 
相關問題