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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With