You need to enable JavaScript to run this app. 如何使用PHP不通过循环从数组中提取包含特定字符的键值对
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PHP不通过循环从数组中提取包含特定字符的键值对

PHP不使用显式循环筛选包含指定字符的数组键值对

实现逻辑

  • 直接调用PHP官方内置的数组处理函数完成筛选,不需要自行编写for/foreach遍历逻辑
  • 用array_filter对数组值做条件校验,自动保留原数组的键名关联关系
  • 字符串包含判断可以用str_contains(PHP 8.0及以上版本),低版本用strpos做兼容

可运行代码示例

<?php
// 定义原始数组
$animal = ['lion', 'elephant', 'tiger'];
// 定义需要检索的字符
$needle = 'io';

// 执行筛选
$matchedItems = array_filter($animal, function ($item) use ($needle) {
    // PHP8.0+写法
    return str_contains($item, $needle);
    // 低版本兼容替换为下面这行即可
    // return strpos($item, $needle) !== false;
});

// 格式化输出结果
foreach ($matchedItems as $key => $val) {
    echo "{$key} - {$val}";
}
?>

输出效果

0 - lion

内容的提问来源于stack exchange,提问作者sudeeshmj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 03:06:03