note 107944 deleted from function.array-search by crell
| From: | crell@php.net | Date: | Thu, 31 Mar 2022 20:38:22 +0000 |
| Subject: | note 107944 deleted from function.array-search by crell | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-217949@lists.php.net to get a copy of this message | ||
Note Submitter: sneskid at hotmail dot com
----
I had an array of arrays and needed to find the key of an element by comparing actual reference.
Beware that even with strict equality (===) php will equate arrays via their elements recursively,
not by a simple internal pointer check as with class objects. The === can be slow for massive arrays
and also crash if they contain circular references.
This function performs reference sniffing in order to return the key for an element that is exactly
a reference of needle.
<?php
function array_ref_search(&$v, array &$s)
{
if(is_object($v)){ return array_search($v, $s, true); }
foreach($s as $rK => &$rV)
{ // reference sniff
$tV = $v;
if( ($rV === ($v = 1)) && ($rV === ($v = 0)) ){
$v = $tV; return $rK; }
$v = $tV;
}
return false; // use null for php < 4.2.0
}
$list = array();
$list['A'] = &$valA; $list['B'] = &$valB;
$valA = 1; $valB = 1;
echo 'array_ref_search: ', array_ref_search($valB, $list), '</br>'; // key
'B'
echo 'array_search: ', array_search($valB, $list, true), '</br>'; //
key 'A'
$valA = array(1,2,3); $valB = array(1,2,3);
echo 'array_ref_search: ', array_ref_search($valB, $list), '</br>'; // key
'B'
echo 'array_search: ', array_search($valB, $list, true), '</br>'; //
key 'A' because ($valA === $valB) is true by elements
$valB[] = &$valB; // circular reference
echo 'array_ref_search: ', array_ref_search($valB, $list), '</br>'; // key
'B'
echo 'array_search: ', array_search($valB, $list, true), '</br>'; //
crash because ($valB === $valB) causes infinite loop
?>