PROFESSOR
PROFESSOR

Reputation: 924

break a word in letters php

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

Answers (4)

Jon Benedicto
Jon Benedicto

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

Alix Axel
Alix Axel

Reputation: 154603

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

Upvotes: 1

moo
moo

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

Seb
Seb

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

Related Questions