你在使用它之前是否需要初始化一个php数组?

时间:2014-04-01 10:26:17

标签: php

我特别想知道:

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

我可以这样做吗:

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

我可以看到它有效,但它是否认为是正确和良好的做法?

2 个答案:

答案 0 :(得分:2)

这不是关于“良好做法”。这两个选项都是有效的(并且不会产生通知)。在第一种情况下,您了解数组数据,因此可以使用array()

明确声明它

但是在常见的情况下,你将无法以这种方式声明数组 - 它可能是动态的 - 它可能具有不同的值,它可能具有不同的维度e t.c.因此,虽然两个选项都是有效的,但第二个将用于许多常见情况,其中数组将保存一些数据,其内容由应用程序逻辑控制。

更多地说 - 拥有数组的几乎所有意义都是 - 保存根据您的应用程序架构和结构构建的动态数据。逻辑。

答案 1 :(得分:-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