如何使用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
相关产品推荐
相关产品推荐

