doubu5035 2009-12-15 21:45 采纳率: 100%
浏览 237
已采纳

在PHP中:如何将一个数组的子集过滤到另一个数组?

foreach ($myarray as $value)
  {
        if (strpos($value,'mysearchstring'))
             //add this $value to new array here
  }

Also where would the second array need to be declared and how?

  • 写回答

8条回答 默认 最新

  • douzhuiqiu4923 2009-12-15 21:48
    关注

    To avoid warnings, the second array should be declared like so

    $newArray = array();
    

    This could be incorporated into your code like so

    $newArray = array();
    foreach ($myarray as $value){
        if (strpos($value,'mysearchstring') !== false ){
             $newArray[] = $value;
        }
    }
    

    Your original code contained an error. strpos returns and false if it doesn't contain the needle, else it returns the index of the occurrence. So strpos($value,'mysearchstring') will return 0 if $value starts with 'mysearchstring' . As PHP will convert 0 to false and visa versa, it will not get added to the array if we use the standard comparisons, so we need to explicitly check that it is false without type conversion (converting 0 to false for example). To do this we use !== (Note the two =)s. This is represented in the code above.

    For more information on comparison operators in php, see the documentation.

    EDIT
    Regarding the commend and usage of [], it ads the new element to the end of the array

    The documentation states that:

    if no key is specified [in the square brackets], the maximum of the existing integer indices is taken, and the new key will be that maximum value plus 1. If no integer indices exist yet, the key will be 0 (zero).

    So if we have an array

    $arr = array(5 => 1, 12 => 2);
    
    //doing this
    $arr[] = 56;
    
    //is exactly the same as doing
    $arr[13] = 56
    
    //As the maximum integer key is 12, so the new key is 13
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(7条)

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号