String: String access and modification by character

String access and modification by character

<?php
// Get the first character of a string
$str = 'This is a test.';
$first = $str[0];

// Get the third character of a string
$third = $str[2];

// Get the last character of a string.
$str = 'This is still a test.';
$last = $str[strlen($str)-1];

// Modify the last character of a string
$str = 'Look at the sea';
$str[strlen($str)-1] = 'e';

?>
  • 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.
  • As of PHP 7.1.0, negative string offsets are also supported. These specify the offset from the end of the string.

Related concepts

String access and modification by character

String: String access and modification by character — Structure map

Clickable & Draggable!

String: String access and modification by character — Related pages: