Jump to content

The Versatility of Square Brackets


iwato

Recommended Posts

In the creation of his hex2bin() function boen_robot employed a technique that made me wonder. The following code is a slight variation of his code designed to illustrate the technique.

<?php	$some_var = md5('apple', 1);	$length = strlen($some_var);	echo var_dump($some_var), '<br /><br />';	for ($i=0; $i<$length; $i++) {		echo var_dump($some_var[$i]), '<br />'; 	}?>

The output from the above code is the following:

string(16) "8p'OlIg(" string(1) "" string(1) "8" string(1) "p" string(1) "" string(1) "'" string(1) "O" string(1) "l" string(1) "I" string(1) "" string(1) "" string(1) "" string(1) "" string(1) "g" string(1) "(" string(1) "" string(1) ""

Notice that no where is there mention of an array.QUESTION: Is this a hidden, undocumented, but acceptable PHP technique?Roddy

Link to comment
Share on other sites

Documented here: http://us3.php.net/manual/en/language.types.string.php

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.
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...