dpwbc42604 2018-10-11 00:11
浏览 52
已采纳

在PHP中使用字符串

Recently, I came across the need of going through a string to act on his letter

As far as I know, a string in PHP is represented as an array of bytes as stated in the doc.

Then I naturally wrote :

$str = 'Hello';
foreach ($str as $letter) {
   doMyThingsOnLetter($letter);
}

Sadly, I got an error saying me that I have provided foreach an invalid argument

I know that this work :

$str = 'Hello';
for($i = 0; $i < strlen($str); $i++) {
   doMyThingsOnLetter($str[$i]);
}

So here, $str is considered as an array but by a foreach we got an error for invalid argument (while it states in the doc it allows arrays)

So I wonder if there is some sort of different type of array for the representation of the string itself in PHP or is it only the way foreach handle array differently ?

PS: I know str_split() exist for this purpose but that's not my concern here

  • 写回答

1条回答 默认 最新

  • duanjue9889 2018-10-11 00:16
    关注

    $str[$i] doesn't treat it as an array. This is just a shorthand notation for substr($str, $i, 1).

    You can use str_split() to get an array of characters from a string:

    foreach (str_split($str) as $letter)
    

    From the documentation:

    Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in $str[42].

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里