Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between $var[] = array() and $var = array()?

Tags:

arrays

php

When I wrote $var = array('index' => 'some value'), it showed me an error when displaying a form on a page on the browser:

Notice: Undefined offset: 0 in C:\xampp\htdocs\learn\php\admin\authors\form.html.php on line 28.

But when I wrote it like this $var[] = array('index' => 'some value'), it showed the page perfectly. So I have to put [] after variable name. In my knowledge, I can create an array variable like this $var = array(some array).

So actually what is the difference between those two?

like image 854
maurisrx Avatar asked Nov 24 '25 15:11

maurisrx


1 Answers

The results are different:

$var = array('index' => 'some value');
var_dump($var);

// array(1) {
//   ["index"]=>
//   string(10) "some value"
// }

$var[] = array('index' => 'some value');
var_dump($var);

// array(1) {
//   [0]=>
//   array(1) {
//     ["index"]=>
//     string(10) "some value"
//   }
// }

If you look closely, the first example creates an associative array with one key pair. The second example creates an array that contains one item at index 0; that one item being the associative array.

like image 93
Salman A Avatar answered Nov 27 '25 03:11

Salman A



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!