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].

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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度