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)
{ $tV = $v;
if( ($rV === ($v = 1)) && ($rV === ($v = 0)) ){
$v = $tV; return $rK; }
$v = $tV;
}
return false; }
$list = array();
$list['A'] = &$valA; $list['B'] = &$valB;
$valA = 1; $valB = 1;
echo 'array_ref_search: ', array_ref_search($valB, $list), '</br>'; echo 'array_search: ', array_search($valB, $list, true), '</br>'; $valA = array(1,2,3); $valB = array(1,2,3);
echo 'array_ref_search: ', array_ref_search($valB, $list), '</br>'; echo 'array_search: ', array_search($valB, $list, true), '</br>'; $valB[] = &$valB; echo 'array_ref_search: ', array_ref_search($valB, $list), '</br>'; echo 'array_search: ', array_search($valB, $list, true), '</br>'; ?>