note 29930 modified in function.array-search by vrana

From: Date: Tue, 17 Aug 2004 14:49:09 +0000
Subject: note 29930 modified in function.array-search by vrana
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-80088@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: <?php 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. --was-- 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://php.net/manual/en/function.array-search.php

« previous php.notes (#80088) next »