note 22411 modified in function.substr by maxim

From: Date: Thu, 08 Aug 2002 23:07:03 +0000
Subject: note 22411 modified in function.substr by maxim
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-34578@lists.php.net to get a copy of this message
When you need a first element (or another one you know the position of) you can do this: $str = 'Maxim Maletsky'; echo '<p>The first letter of my name is (' . $str[0] . ')'; // This prints: // First letter of my name is (M) // // This example is the same as substr($str, 0, 1); --- // Now, the same thing is when you need to find out the last letter: echo '<p>The last letter of my name is (' . $str[strlen($str)-1] . ')'; // This prints: // First letter of my name is (y) // // This example is the same as substr($str, -1); --- This example can explain it better: for($i=0; $i<strlen($str); $i++) { echo "<br> Character [$i] is (" . $str[$i] . ")"; } Using this instead of substring might help you a bit not to create too many confusion. Maxim Maletsky maxim@php.net --was-- When you need a first element (or another one you know the position of) you can do this: $str = 'Maxim Maletsky'; echo '<p>The first letter of my name is (' . $str[0] . ')'; // This prints: // First letter of my name is (M) // // This example is the same as substr($str, 0, 1); --- // Now, the same thing is when you need to find out the last letter: echo '<p>The last letter of my name is (' . $str[strlen($str)-1] . ')'; // This prints: // First letter of my name is (y) // // This example is the same as substr($str, -1); --- Now, try this out: for($i=0; $i<strlen($str); $i++) { echo "<br> Character [$i] is (" . $str[$i] . ")"; } This happens because PHP is a C based language, and see thinks this way. Using this instead of substring when you can will help you a bit not to create too many confusion. Maxim Maletsky maxim@php.net http://www.php.net/manual/en/function.substr.php

« previous php.notes (#34578) next »