We need to find the index of the element in the nested array, where the elements are constructed as follows:
array = [
index = & gt; [line1, line2]
]
Moreover, the search string is checked against the string1
element of this array. It was thought that the following construction could be passed as the first parameter: [string, '(. *)']
, where (. *)
is any string. Why doesn’t it work?
$ arr = [
'1' = & gt; ['a', '1'],
'2' = & gt; ['b', '2']
];
echo array_search (['a', '(. *)'], $ arr);
Answer 1, authority 100%
echo array_search (['a', '(. *)'], $ arr);
The specified construct searches for an element with the value ['a', '(. *)']
in the $ arr
array.
The first $ needle parameter in array_search is the value to search.
Naturally, there is no such value in the $ arr
array, so the result is array_search
false.
Can you tell us in more detail what exactly from such an array you need to find?
$ arr = [ '1' = & gt; ['a', '1'], '2' = & gt; ['b', '2'] ];
If you want to find the index of the element ‘b’:
foreach ($ arr as $ index = & gt; $ value) {
if (is_array ($ value)) {
if (($ i = array_search ('b', $ value))! == false) {
echo 'First index:'. $ index. PHP_EOL;
echo 'Second index:'. $ i. PHP_EOL;
var_dump ($ arr [$ index] [$ i]); // element to search for
}
}
}
Answer 2
class SearchArray {
private $ param = null;
public function __construct ($ search) {
$ this- & gt; param = $ search;
}
public function searchArray ($ a) {
if (array_search ($ this- & gt; param, $ a)! == false) {
return true;
}
}
}
$ math = array_filter ($ arr, array (new SearchArray ('a'), 'searchArray'));
var_dump ($ math);
you can try it.