A

PHP search by value

public
andrei.k Feb 02, 2024 Never 16
Clone
PHP 1.php 45 lines (37 loc) | 696 Bytes
1
<?php
2
3
$array = [
4
[
5
'id' => 1,
6
'name' => 'BMW',
7
],
8
[
9
'id' => 2,
10
'name' => 'Zeekr',
11
],
12
[
13
'id' => 3,
14
'name' => 'Lexus',
15
],
16
[
17
'id' => 4,
18
'name' => 'Volvo',
19
],
20
];
21
22
$search = 'Lexus';
23
24
$find1 = array_filter($array, function($v) use ($search) {
25
return $v['name'] == $search;
26
});
27
28
$index = array_search($search, array_column($array, 'name'));
29
$find2 = $array[$index];
30
31
function search($array, $key, $value) {
32
foreach ($array as $v) {
33
if ($v[$key] === $value) {
34
return $v;
35
}
36
}
37
38
return null;
39
}
40
41
$find3 = search($array, 'name', $search);
42
43
var_dump($find1);
44
var_dump($find2);
45
var_dump($find3);