note 107944 added to function.array-search

From: Date: Thu, 15 Mar 2012 20:50:58 +0000
Subject: note 107944 added to function.array-search
Groups: php.notes 
Request: Send a blank email to php-notes+get-186695@lists.php.net to get a copy of this message
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 ?> ---- Server IP: 72.55.140.6 Probable Submitter: 69.159.196.196 ---- Manual Page -- http://www.php.net/manual/en/function.array-search.php Edit -- https://master.php.net/note/edit/107944 Del: integrated -- https://master.php.net/note/delete/107944/integrated Del: useless -- https://master.php.net/note/delete/107944/useless Del: bad code -- https://master.php.net/note/delete/107944/bad+code Del: spam -- https://master.php.net/note/delete/107944/spam Del: non-english -- https://master.php.net/note/delete/107944/non-english Del: in docs -- https://master.php.net/note/delete/107944/in+docs Del: other reasons-- https://master.php.net/note/delete/107944 Reject -- https://master.php.net/note/reject/107944 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#186695) next »