Page 109 - Open Soource Technologies 304.indd
P. 109
Unit 5: Strings
Notes
$a = array(‘name’ =>
‘Piyush’, ‘age’ => 35, ‘wife’ => ‘Seema’);
print_r($a);
Array ( [name] => Piyush [age] => 35 [wife] => Seema)
Using print_r( ) on an array moves the internal iterator to the position of the last element in the
array.
When you print_r( ) an object, you see the word Object, followed by the initialized properties of
the object displayed as an array.
class P { var $name = ‘nat’; // ... } $p = new P; print_r($p); Object ( [name] => nat)
Boolean values and NULL are not meaningfully displayed by print_r( ):
print_r(true); print “\n”; 1 print_r(false); print “\n”; print_r(null); print “\n”;
For this reason, var_dump( ) is preferable to print_r( ) for debugging. The var_dump( ) function
displays any PHP value in a human-readable format.
var_dump(true);
bool(true) var_dump(false);
bool(false);
var_dump(null);
bool(null);
var_dump(array(‘name’ => Pradip, ‘age’ => 35));
array(2)
{ [“name”]=> string(4) “Pradip” [“age”]=> int(35) }class P { var $name = ‘Nat’; // ... } $p = new P;
var_dump($p); object(p)(1) { [“name”]=> string(3) “Nat”
}
Beware of using print_r( ) or var_dump( ) on a recursive structure such as $GLOBALS (which has
an entry for GLOBALS that points back to itself ). The print_r( ) function loops infinitely, while
var_dump( ) cuts off after visiting the same element three times.
5.3 Accessing Individual Characters
The strlen( ) function returns the number of characters in a string:
$string = ‘Hello, world’; $length = strlen($string); // $length is 12
$string = ‘Hello’; for ($i=0; $i < strlen($string); $i++) { printf(“The %dth character is %s\n”, $i,
$string[$i]); } The 0th character is H The 1th character is e The 2th character is l The 3th character
is l The 4th character is o
$string = ‘Hello’;
for ($i=0; $i < strlen($string); $i++) {
printf(“The %dth character is %s\n”, $i, $string[$i]);
LOVELY PROFESSIONAL UNIVERSITY 103