note 29930 added to function.array-search

From: Date: Sat, 01 Mar 2003 02:46:20 +0000
Subject: note 29930 added to function.array-search
Groups: php.notes 
Request: Send a blank email to php-notes+get-44684@lists.php.net to get a copy of this message
If you're interested in finding a line in a file, after you read it into an array using file(), you can not use array_search since the match should be exact, and lines have line-endings ('\n', '\r' or '\n\r') - or else you know for sure what your lines contain physically. The solution is to traverse the whole array, trim() each entry and then use array_search() - or - use something like the following small function I wrote for myself: function search_array($needle, $haystack) { if (!is_array($haystack) || !is_string($needle)) return false; // not valid argument types @reset($haystack); while (list ($key, $value) = each($haystack)) { $value = trim($value); // remove spaces from the beginning and the end if ($value === $needle) return $key; // $needle was found, return the key } return false; // no $needle was found in $haystack } ----------------------------- Notes: 1. you should check the return value with === since 0 as a key equals to 'false'. i.e. if (search_array('my_line', $my_array) === false) { ... } 2. I have no need in whitespace at the beginning of the line, therefore I use trim(). If it's important to you, use rtrim() or chop() instead. - - Sergey. -- http://www.php.net/manual/en/function.array-search.php http://master.php.net/manage/user-notes.php?action=edit+29930 http://master.php.net/manage/user-notes.php?action=delete+29930 http://master.php.net/manage/user-notes.php?action=reject+29930

« previous php.notes (#44684) next »