tags:

views:

424

answers:

4

I want to accept a string from a form and then break it into an array of characters using PHP, for example:

$a = 'professor';
$b[0] == 'p';
$b[1] == 'r';
$b[2] == 'o';
.
.
.
.
.
$b[8] = 'r';
+19  A: 

You don't need to do that. In PHP you can access your characters directly from the string as if it where an array:

$var = "My String";
echo $var[1]; // Will print "y".
Seb
I didn't know that. good tip.
gargantaun
FYI, $var{1} will work, but it's being deprecated as of PHP6 in favor of $var[1].
whichdan
+9  A: 
str_split($word);

This is faster than accessing $word as an array. (And also better in that you can iterate through it with foreach().) Documentation.

orlandu63
Why is it faster? It just returns an array.
St. John Johnson
It is not faster; in fact, it's slower - it has to create an additional array and see where to split the original string depending on the second parameter.
Seb
You're correct: a benchmark confirms that this is 50% slower than your method.
orlandu63
A: 

Be careful because the examples above only work if you are treating ASCII (single byte) strings.

Alix Axel
A: 

If you really want the individual characters in a variable of array type, as opposed to just needing to access the character by index, use:

$b = str_split($a)

Otherwise, just use $a[0], $a[1], etc...

Jon Benedicto
thanks for the answer............it worked
PROFESSOR