PHP Search for an array key by a value from a part of a word
There is such a problem.
An array of data consisting of URLs:
array(8) {
[0]=>
string(39) "/update/data?drid=2759&nc=1597034659"
[1]=>
string(42) "/update/nodata?drid=2759&nc=1597034659"
}
As you can see at the end, the values are constantly changing when the page is reloaded. I need to find the array key by part of a string of these addresses.
You should get something like:
array_search('data', $array); // 0
array_search('nodata', $array); // 1
I tried to search through array_search and into it through strpos for the desired value, but the result is zero.
Is this even possible or not? I'll be glad to any help)
1
2 answers
Solution
$name='data';
foreach($array as $key => $value) {
if(strpos($value, mb_convert_encoding($name, 'cp1251, 'utf-8)) !== false) {
var_dunp($key);
}
}
Thank you to the user Bloom
0
Author: VaDoSiQ, 2020-08-10 05:54:25
Depending on which search you want to use, substitute your own in the callback function. For example, a regular or like me.
$arr = array(
"/update/data?drid=2759&nc=1597034659",
"/update/nodata?drid=2759&nc=1597034659"
);
function findKey($arr, $needle) {
return array_keys(
array_filter(
$arr,
function ($element) {
return strpos($element, $needle) !== false;
}
)
);
}
var_dump(findKey($arr, 'data'));
0
Author: Dmitry Lin, 2020-08-10 06:01:54