Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Modify String With Array Syntax

<?php

$a = '1';
$a[1] = 2;
$a[10] = 3;
$a[-9] = 4;

print $a;
// 124       3

PHP strings allows access to individual characters using the array syntax: $string[$index].

It is also possible to modify the string with the same syntax: the index have to be integers.

The positive integers are offsets, starting at zero. Any missing characters between the end of the string and the requested index is set to space ' '. Negative index are also valid, starting from the end of the string.

Here, $a[1] is just after the end of the string, $a[10] is well beyond the end of the string, and $a[-9] is almost back to the beginning of the string.

See Also

PHP Features

Last updated: 10 September 2026