Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this assignment work?

Tags:

php

I don't know whether something similar has been asked.Can someone explain how the assignment works in the following cases:

$a = "1"; $a[$a] = "2"; echo $a;

This gives output : 12

$a = "1"; $a[$a] = 2; echo $a;

This gives output : 12

$a = 1; $a[$a] = 2; echo $a;

This gives output: E_WARNING : type 2 -- Cannot use a scalar value as an array -- at line 6 1

like image 539
Sp0T Avatar asked Jun 26 '15 06:06

Sp0T


1 Answers

The first two examples you have provided are using strings. Strings can be treated as an array and characters accessed by their integer positions.

In the third example, you're assigning $a as an integer which has no character positions to reference.

like image 81
mproffitt Avatar answered Oct 15 '22 02:10

mproffitt