0

I have simple code:

<?php
error_reporting(E_ALL);
ini_set('display_errors', true);
ini_set('html_errors', false);
$test = array();
$test = 'demo';
$test['55test'] = 'yay';
var_dump($test);

returns

 string(56) "demo                                                   y"

I know this is not proper way to convert string to array, but it seems that I've missed PHP docs about this case. Can anyone enlighten me regarding this? Thanks

P.S. Tested in PHP 5.3.6-13

2 Answers 2

1

String access and modification by character

Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in $str[42]. Think of a string as an array of characters for this purpose. The functions substr() and substr_replace() can be used when you want to extract or replace more than 1 character.

Check the string manual

1

If you make this assignment:

$test['55'.'test'] = 'yay';

The following happen:

  • Content of [] is converted to int and (int)('55test') gives 55.
  • Positions from 3 to 54 are not set. You are assigning to position 55 so they are all set to spaces.
  • $test[55] = 'yay' results in $test[55] === 'y' because only one character of 'yay' can be assigned to a single position in a string and the first one is selected.

Note there is no conversion of array to string. It is just that string can be accessed as array.

(this has been written before answer update)

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.