What does PHP syntax $var1[] = $var2 mean?

What does PHP syntax $var1[] = $var2 mean?

Note the [] after $var1 varable.


It means that $var1 is an array, and this syntax means you are inserting $var2 into a new element at the end of the array.

So if your array had 2 elements before, like this:

$var1=( 1 => 3, 2 => 4)

and the value of $var2 was 5, it would not look like this:

$var1=( 1 => 3, 2 => 4, 3 => 5)

It also means that if $var2 was an array itself, you have just created a two dimensional array. Assuming the following:

$var1=( 1 => 3, 2 => 4)
$var2=( 1 => 10, 2=>20)

doing a $var1[]=$var2; wouls result in an array like this:

$var1=( 1 => 3, 2 => 4, 3 => (1 =>10, 2 => 20))

As an aside, if you haven't used multi-dimensional arrays yet, accessing the data is quite simple. If I wanted to use the value 20 from our new array, I could do it in this manner:

echo $var1[3][2];

Note the second set of square brackets - basically you are saying I want to access element two of the array inside element 3 of the $var1 array.

On that note, there is one thing to be aware of. If you are working with multi-dimensional arrays, this syntax can catch you out inside a loop structure of some sort. Lets say you have a two dimensional array where you store some records and want to get more from the database:

$var1 = ( 
    1 => (id =>1, age => 25, posts => 40),
    2 => (id =>2, age => 29, posts => 140),
    3 => (id =>3, age => 32, posts => 12)
    )

A loop like this following:

while($row=someDatabaseRow)
{
    $var1[]=$row['id']; // value 4
    $var1[]=$row['age']; // value 21
    $var1[]=$row['posts']; // value 34
}

will infact insert a new element for every execution, hence your array would end up looking like this:

$var1 = ( 
    1 => (id =>1, age => 25, posts => 40),
    2 => (id =>2, age => 29, posts => 140),
    3 => (id =>3, age => 32, posts => 12),
    4 => 4,
    5 => 21,
    6 => 34
    )

The correct way would be to assemble the array first, then append it to your current array to maintain the strucutre, like this:

while($row=someDatabaseRow)
{
    $tempArr= array();
    $tempArr[]=$row['id']; // value 4
    $tempArr[]=$row['age']; // value 21
    $tempArr[]=$row['posts']; // value 34
    $var1[]=$tempArr;
}

Now your array would look like you expected, namely:

$var1 = ( 
    1 => (id =>1, age => 25, posts => 40),
    2 => (id =>2, age => 29, posts => 140),
    3 => (id =>3, age => 32, posts => 12)
    4 => (id =>4, age => 21, posts => 34)
    )

这意味着你正在将var2的值推送到数组var1


That's shorthand for array_push()

It will make $var1 and array (if it isn't already) and push $var2 in to it.

链接地址: http://www.djcxy.com/p/9976.html

上一篇: 从字符串中删除最后一个字符

下一篇: PHP语法$ var1 [] = $ var2是什么意思?