note 100701 added to function.array-search

From: Date: Mon, 01 Nov 2010 10:18:10 +0000
Subject: note 100701 added to function.array-search
Groups: php.notes 
Request: Send a blank email to php-notes+get-173635@lists.php.net to get a copy of this message
Hey all - I needed a function to search for an array in a multi-dimensional array, but only the keys I wanted, not all keys. Hee if my function: <?php function my_array_search($needle, $haystack) { if (empty($needle) || empty($haystack)) { return false; } foreach ($haystack as $key => $value) { $exists = 0; foreach ($needle as $nkey => $nvalue) { if (!empty($value[$nkey]) && $value[$nkey] == $nvalue) { $exists = 1; } else { $exists = 0; } } if ($exists) return $key; } return false; } ?> Examples: <?php $needle = array('date_start' => '27-10-2010', 'date_end' => '29-10-2010'); $haystack = array(); $haystack[] = array('date_start' => '25-10-2010', 'date_end' => '26-10-2010', 'promos' => array('test', 'test1'); $haystack[] = array('date_start' => '27-10-2010', 'date_end' => '28-10-2010', 'promos' => array('test2', 'test3'); $haystack[] = array('date_start' => '27-10-2010', 'date_end' => '29-10-2010', 'promos' => array('test4', 'test5'); $key = my_array_search($needle, $haystack); // will output (bool)false for not found or (int)key_no with the key number // this example outputs (int)2 var_dump($key); ?> I hope this function will help someone! ---- Server IP: 69.147.83.197 Probable Submitter: 89.123.51.169 ---- Manual Page -- http://www.php.net/manual/en/function.array-search.php Edit -- https://master.php.net/note/edit/100701 Del: integrated -- https://master.php.net/note/delete/100701/integrated Del: useless -- https://master.php.net/note/delete/100701/useless Del: bad code -- https://master.php.net/note/delete/100701/bad+code Del: spam -- https://master.php.net/note/delete/100701/spam Del: non-english -- https://master.php.net/note/delete/100701/non-english Del: in docs -- https://master.php.net/note/delete/100701/in+docs Del: other reasons-- https://master.php.net/note/delete/100701 Reject -- https://master.php.net/note/reject/100701 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#173635) next »