0

I was just playing with PHP array

$arr = array(); 
$arr['a'] = 'hello';
$arr['a']['b'] = 'world';
var_dump($arr);

This code gives the following error in PHP 5.5.15

Warning: Illegal string offset 'b'

I can guess the reason. (As $arr['a'] is not an array). Thats fine.

But i am confused by the output,

array (size=1)
  'a' => string 'wello' (length=5) 

Where is this wello coming from ?

3 Answers 3

3

This is because

(int)'b' === 0

'b' is silently casted to integer (after the warning was printed) and $arr['a'][0] sets the first symbol of string to what it could—to the first byte of given string, which is apparently 'w'.

Sign up to request clarification or add additional context in comments.

Comments

3

$arr['a'] already exists as a string

$arr['a']['b'] is therefore referencing offset b in a string

Characters in Strings can be referenced using array-style syntax as though they are an array of characters, so $arr['a']['b'] is trying to reference a character in the string at $arr['a']

Offsets in a string are numeric; b is not numeric, hence the warning

PHP is forgiving, and will cast b to a numeric (0) so that it can access a character in the string

So character 0 in the string becomes the first character of the value you assigned (world)

So hello becomes wello

Comments

2

This is pretty simple! You can access the string in your array as an array so:

echo $arr["a"][0]; //Output: h

So with the index 'b' it's just get's casted to a int, so it takes 0 and overwrites it with 'w'

You even see this example in the manual: http://php.net/manual/en/language.types.type-juggling.php

And a quote from there:

<?php
$a    = 'car'; // $a is a string
$a[0] = 'b';   // $a is still a string
echo $a;       // bar
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.