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';
From stackoverflow
-
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".gargantaun : I didn't know that. good tip.whichdan : FYI, $var{1} will work, but it's being deprecated as of PHP6 in favor of $var[1]. -
str_split($word);This is faster than accessing $word as an array.(And also better in that you can iterate through it withforeach().) Documentation.St. John Johnson : Why is it faster? It just returns an array.Seb : 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.orlandu63 : You're correct: a benchmark confirms that this is 50% slower than your method. -
Be careful because the examples above only work if you are treating ASCII (single byte) strings.
-
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...
PROFESSOR : thanks for the answer............it worked
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.