duancan65665 2012-11-13 07:45
浏览 53
已采纳

理解条纹偏移?

Let's say I've a small array () :

    $array = array(
        'Pantin',
        'Paris',
        'Paris',
        'Puhahaa',
        'Ptdr',
        'Roumanie',
        'Rlolo'
    );

What I want to do? Simply get all words that start with the 'r' letter

$dataLen = sizeof($array);
$results = array();

for ($i = 0; $i < $dataLen && count($array) < 10; $i++) {
    if (stripos($array[$i], 'r', 0)) { // 

        array_push($results, $array[$i]); 
    }
}

print_r($results); // Output : Array ( [0] => Paris [1] => Paris [2] => Ptdr )

I can't understand.. I put 0 as the offset, but it gives me words that start with the P letter and that "contain" the R letter.

  • 写回答

2条回答 默认 最新

  • duanqu9292 2012-11-13 07:50
    关注

    Zero is the default value, so these things are equivalent;

    stripos($array[$i], 'r', 0)
    stripos($array[$i], 'r') // Same
    

    That is, they start at position 0 and try to find the letter r or R. If it is not on position 0, they check the second letter, then the third letter etc.

    Stripos returns the position of the found letter. For Paris is returns 2, for Rlolo it returns 0. If it is not found it returns false.

    By default, 0 and false are both interpreted as false. So if the first letter is R, stripos returns 0 and the if statement is not executed. To solve this, use this code:

    if (stripos($array[$i], 'r') !== false) { ... }
    

    If you want to check just the first letter and not the subsequent letters, you can do something like this:

    $word = $array[$i];
    $firstLetter = $word[0];
    if ($firstLetter == 'r' || $firstLetter == 'R') { ... }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • duai5344 2012-11-13 07:52
    关注

    Another method would be using array_filter with a callback.

    $results = array_filter($array, function($var) {
        return strtolower($var[0]) == 'r';
    });
    

    (Of course you could also use return stripos($var, 'r') === 0;)

    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Erasure Code纠删码表
  • ¥15 用vite创建的vue3项目,404重定向不起作用??
  • ¥15 关于#c语言#的问题:一个球从80米高度自由落下,每次落地后反弹的高度为原高度的一半计算6次小球反弹的高度.(反弹结果取整,使用走走for循环结构)
  • ¥15 SurfaceControl的screenshot问题
  • ¥15 基于51单片机的oled菜单代码,要C语言,模块化编程!
  • ¥15 JAVAswing,设计一个扑克牌什么的
  • ¥50 python ctypes调用dll实现分析
  • ¥40 用python解决数据统计问题
  • ¥100 是否有方案能通过抓包分析得到移动应用的名称和包名信息?
  • ¥15 opencv检测不到轮廓