Reputation: 924
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';
Upvotes: 3
Views: 8536
Reputation: 10582
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...
Upvotes: 3
Reputation: 154603
Be careful because the examples above only work if you are treating ASCII (single byte) strings.
Upvotes: 1
Reputation: 7789
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.
Upvotes: 9
Reputation: 25147
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".
Upvotes: 27