Laravel中是否存在替代PHP原生in_array函数的等效方法?
in_array的方法 Hey there! I totally get where you're coming from—switching to Laravel's helper methods can feel a bit tricky when you're used to native PHP functions. Let's clear this up:
First, the reason Str::contains didn't work for you is that it's designed for string operations, not arrays. It checks if a string contains a given substring (or any substring from an array), which is a completely different use case than in_array.
Luckily, Laravel has two great alternatives for in_array:
1. Arr::contains (数组助手类)
This is the closest direct replacement for in_array since it works directly with native PHP arrays. It even supports strict type checking just like in_array's third parameter.
Examples:
- 基础检查:
use Illuminate\Support\Arr; Arr::contains(['apple', 'banana', 'cherry'], 'banana'); // 返回 true - 严格类型检查(对应
in_array($needle, $haystack, true)):Arr::contains([1, 2, 3], '1', true); // 返回 false(因为'1'是字符串,不是整数)
2. Collection 的 contains() 方法
如果你在处理集合(这在Laravel中非常常见),可以直接使用集合内置的contains()方法。先把数组转成集合,再调用方法即可:
Examples:
- 基础值检查:
collect(['apple', 'banana', 'cherry'])->contains('banana'); // 返回 true - 检查关联数组的键值对:
collect([ ['name' => 'John', 'age' => 30], ['name' => 'Jane', 'age' => 25] ])->contains('name', 'Jane'); // 返回 true - 用回调做复杂检查:
collect([1, 2, 3, 4])->contains(function ($value, $key) { return $value > 2; }); // 返回 true
两种方法都很实用——如果处理原生数组就用Arr::contains,如果已经在使用Laravel集合做链式操作,就选集合的contains()。
内容的提问来源于stack exchange,提问作者Petro Gromovo

