Did you know.........?

Did you know that a string is actually an array of characters?

$str = 'Hello World';
echo $str[6] . $str[1] . $str[2] . $str[2] . '?';

I don’t see this taught anywhere and not sure where or how you might want to use this. If you know of a use case post it here.


Not really “taught” as much as “mentioned” I guess


The string in PHP is implemented as an array of bytes and an integer indicating the length of the buffer. It has no information about how those bytes translate to characters, leaving that task to the programmer.

I can’t think of any offhand at the moment. From what I can recall using native string functions has always been enough for what I’ve wanted done, PHP anyway. I vaguely remember working with string arrays in JavaScript but it was so long ago I don’t remember any specifics. (probably was a newbie hack :wink: )

It can be used as a shorthand for identifying the leading character of a string - so for example, if you want your script to react to commands that start with !, you could say
if(substr($input,0,1) == "!")
but you could accomplish the same with
if($input[0] == "!")

Under the hood, this is likely how commands like substr, or case-conversion commands work, effectively shorthanding (SUPER simplified…)

for($i = 0; $i < len($input); $i++) {
  if(ord($input[$i]) >= 65 && ord($input[$i]) <= 90) {
   $input[$i] = chr(ord($input[$i])+32);

(This is the array-manipulation form of strtolower in the default locale)


I didn’t know that.

It’s interesting that

…works, as does

echo $string[1];

But you can’t do a foreach on a string.

	foreach($string as $char){
		echo "$char<br>";

That gives an error.
There is probably a good reason. PHP is loose, but not that loose that you can always treat a string like an array.

When I am on my desktop I am going to try the following:

foreach( (array) $string as $char){
   echo "$char<br>";

Watch this space :slight_smile:

I can already tell you it will work. And you can still access the indices.

$string = 'Hello World';
foreach( (array) $string as $str){
echo $str[6] . $str[1] . $str[2] . $str[2] . '?';

mmh… except that hasnt worked as John thinks it will.

If it had worked, $str wouldnt be an array, it would be a single character.

(array) $string will cast as though [$string](as is true of any scalar value).

It’s probably safe to say that a string is indexable, but does not implement the Traversable class, and is not an array, and therefore is not traversable with foreach.

1 Like

Yeah i knew that. A perfect use case is to give just a single character of a string when you expect the first item of an array, and producing a lot of wasted time for newbies and those not aware of this.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.