 |
array_search (PHP 4 >= 4.0.5, PHP 5) array_search --
在数组中搜索给定的值,如果成功则返回相应的键名
说明mixed array_search ( mixed needle, array haystack [, bool strict] )
在 haystack 中搜索
needle 参数并在找到的情况下返回键名,否则返回 FALSE。
注意:
如果 needle 是字符串,则比较以区分大小写的方式进行。
注意:
在 PHP 4.2.0 之前,array_search() 在失败时返回
NULL 而不是 FALSE。
如果可选的第三个参数 strict 为 TRUE,则
array_search() 还将在 haystack
中检查 needle 的类型。
如果 needle 在
haystack
中出现不止一次,则返回第一个匹配的键。要返回所有匹配值的键,应该用
array_keys() 加上可选参数
search_value 来代替。
例 1. array_search() 例子
<?php $array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2; $key = array_search('red', $array); // $key = 1; ?>
|
|
| 警告 | 本函数可能返回布尔值
FALSE,但也可能返回一个与 FALSE 等值的非布尔值,例如
0 或者 ""。请参阅布尔类型章节以获取更多信息。应使用
=== 运算符来测试本函数的返回值。 |
参见 array_keys(),array_values(),array_key_exists()
和 in_array()。
xurizaemon
13-Jul-2007 01:11
@ ben, your array_isearch function returns the value, while array_search returns the key. to get equivalent (but case-insensitive) functionality, you would return $k not $v.
ben at reload dot me dot uk
25-May-2007 06:50
A refinement on chappy at citromail dot hu's case-insensitive search function...
<?php
function array_isearch($str,$array){
foreach ($array as $k=>$v) {
if (strtolower($v) == strtolower($str)) { return $v; };
};
return false;
}
?>
Shall return false on no match or return the first value that matches if one or more matches are found (same functionality as the array_search() function). It is also more efficient as it stops searching the array once a match is found.
php5 site builder
23-May-2007 05:14
If you encounter a situation where condition test is failing on the result of either array_search or in_array, even when using "===" and "!==", make sure to set $strict = true in your array_search() or in_array() function call.
A situation such as :
$arTemp[0] = 1;
$arTemp[1] = 0;
$arTemp[2] = 3;
$arTemp[3] = 5;
$sTempTest = 'BLAH';
$bResult = in_array($sTempTest,$arTemp);
$bResult2 = array_search($sTempTest,$arTemp);
var_dump($bResult);
var_dump($bResult2);
will result in :
boolean true
int 1
Using :
$bResult = in_array($sTempTest,$arTemp,true);
$bResult2 = array_search($sTempTest,$arTemp,true);
will yield :
boolean false
boolean false
This is necessary in any instance where you have an array value equal to the integer zero. As soon as you put the zero in quotes or double quotes (a string), the evaluation works with in_array & array_search without the $strict parameter being set.
rob at robspages dot net
16-Feb-2007 05:49
php dot net at surfnation dot de's function with a slight mod to correct for axo at axolander dot de's comments:
<?php
function multiArraySearch($needle, $haystack){
$value = false;
$x = 0;
foreach($haystack as $temp){
$search = array_search($needle, $temp);
if (strlen($search) > 0 && $search >= 0){
$value[0] = $x;
$value[1] = $search;
}
$x++;
}
return $value;
}
?>
axo at axolander dot de
14-Feb-2007 01:32
to php dot net at surfnation dot de
please make sure you read the warning on array_search - your multi-dimensional function will not return anything if the first element is the one you're looking for.
php dot net at surfnation dot de
03-Feb-2007 11:03
Here is my solution for a 2-dimensional search.
It combines the foreach with the faster array_search (I did use a recursive way, cause I am at war with it :) ).
it is quick, easy and (hopefully) very stable.
<?php
$map = array();
$map[1][1] = 11;
$map[2][1] = 21;
$map[3][1] = 31;
$map[1][3] = 13;
$varGesuchtesElement = 21;
$varGefundenesElement = fktMultiArraySearch($map,$varGesuchtesElement);
if ($varGefundenesElement){
print_r($varGefundenesElement);
}
else{
echo "Kein Element gefunden!";
}
function fktMultiArraySearch($arrInArray,$varSearchValue){
foreach ($arrInArray as $key => $row){
$ergebnis = array_search($varSearchValue, $row);
if ($ergebnis){
$arrReturnValue[0] = $key;
$arrReturnValue[1] = $ergebnis;
return $arrReturnValue;
}
}
}
?>
elvenone at gmail dot com
27-Jan-2007 01:10
<?php
function array_reverse_search($value, $array) {
for($i = sizeof($array)-1; $i>=0; $i--) {
if ($array[$i] == $value) return $i;
}
return -1;
}
?>
francois at tekwire dot net
18-Jan-2007 10:34
Please note that, in PHP5, if you search for an object in an array using the array_search() function, PHP will return the first object whose properties match, not the same class and instance as your needle. In other words, the object comparison is of type '==', not '===' (see the 'Comparing objects' page).
erick dot xavier at gmail dot com
04-Jan-2007 12:57
Modifing the "multiarray_search" to unordered Array....
<?PHP
function multiarray_search($arrayVet, $campo, $valor){
while(isset($arrayVet[key($arrayVet)])){
if($arrayVet[key($arrayVet)][$campo] == $valor){
return key($arrayVet);
}
next($arrayVet);
}
return -1;
}
//I.e.:
$myArr = array(
13 => array(
"fruit" => "banana"
),
654 => array(
"fruit" => "apple"
),
2445 => array(
"fruit" => "nothing more"
)
);
print(multiarray_search($myArr , "fruit", "apple"));
/*
Output:
654
*/
//and
print(multiarray_search($myArr , "fruit", "orange"));
/*
Output:
-1
*/
?>
otto at twbc dot net
14-Dec-2006 07:06
Unlimited depth array regular expression search, I found it useful, perhaps someone else will too. Searches on the array values only. Key search could be easily added.
function Array_Search_Preg( $find, $in_array, $keys_found=Array() )
{
if( is_array( $in_array ) )
{
foreach( $in_array as $key=> $val )
{
if( is_array( $val ) ) $this->Array_Search_Preg( $find, $val, $keys_found );
else
{
if( preg_match( '/'. $find .'/', $val ) ) $keys_found[] = $key;
}
}
return $keys_found;
}
return false;
}
joltmans at bolosystems dot com
06-Dec-2006 11:25
You can use array_search to simply parse a CLI program's input parameters such as:
[user@server ~]$ ./someCLIprog.php --username user1 --password 123password --option1 whatever
You can easily parse this information using the following code snippets:
<?php
// Get the username
$userkey = array_search("--username", $argv);
// Make sure both that the token was found and followed by another valid token, AKA not one that begins with a -
if ($userkey && !empty($argv[$userkey+1]) && strcmp($argv[$userkey+1]{0}, '-')) {
$username = $argv[$userkey+1];
}
// If you want the token to be required add the following else statement
else {
exit("No username provided\n");
}
// repeat for each optional parameter,
?>
evert_18 at hotmail dot com
13-Nov-2006 02:18
This function can search in multidimensional arrays, no mather how multidimensional the array is!
<?php
function array_search(&$array,$needle)
{
foreach($array as $key => $value)
{
if($value == $needle || $key == $needle)
return(true);
else
if(is_array($value))
$this->search($value,$needle);
else
return(false);
}
}
?>
dmitry dot polushkin at gmail dot com
22-Oct-2006 05:03
To get the key of the found search value, use:
<?php
$a = array('a', 'b', 'c');
echo array_search(array_search('c', $a), array_keys($a));
?>
jupiter at nospam dot com
29-Sep-2006 09:25
Checks that array value STARTS with the string(needle), while other functions require an exact match OR the needle can be anywhere within. This function can be manipulated to END with the needle if needed
<?php
// returns first key of haystackarray which array valuestring starts with needlestring, is case-sensitive
function arrayHaystackStartsWithNeedleString($haystackarray, $needlestring) {
if (is_array($haystackarray)) { // confirms array
$needlelength = strlen($needlestring); // length of string needle
foreach ($haystackarray as $arraykey => $arrayvalue) { // gets array value
$arraypart = substr($arrayvalue, 0, $needlelength); // first characters of array value
if ($needlestring == $arraypart) { // did we find a match
return $arraykey; // return will stop loop
} // end match conditional
} // end loop
} // end array check
return false; // no matches found if this far
}
?>
I haven't speed tested this, but it should be pretty quick.
Digitally Designed dot co dot uk
28-Sep-2006 09:48
My Function to search a Multidimensional array.
Pass in :
$theNeedle as what you want to find.
$theHaystack as the array
$keyToSearch as what key in the array you want to find the value in.
<?
function myMulti_Array_Search($theNeedle, $theHaystack, $keyToSearch)
{
foreach($theHaystack as $theKey => $theValue)
{
$intCurrentKey = $theKey;
if($theValue[$keyToSearch] == $theNeedle)
{
return $intCurrentKey ;
}
else
{
return 0;
}
}
}
?>
lars-magne
22-Sep-2006 12:19
Further comments on the multidimensional array searches given earlier:
I needed an extended search function which could search in both keys and values in any # dimension array and return all results. Each result contains key/value hit, type (key or value), key path and value (in case result is a key).
<?php
function array_search_ext($arr, $search, $exact = true, $trav_keys = null)
{
if(!is_array($arr) || !$search || ($trav_keys && !is_array($trav_keys))) return false;
$res_arr = array();
foreach($arr as $key => $val)
{
$used_keys = $trav_keys ? array_merge($trav_keys, array($key)) : array($key);
if(($key === $search) || (!$exact && (strpos(strtolower($key), strtolower($search)) !== false))) $res_arr[] = array('type' => "key", 'hit' => $key, 'keys' => $used_keys, 'val' => $val);
if(is_array($val) && ($children_res = array_search_ext($val, $search, $exact, $used_keys))) $res_arr = array_merge($res_arr, $children_res);
else if(($val === $search) || (!$exact && (strpos(strtolower($val), strtolower($search)) !== false))) $res_arr[] = array('type' => "val", 'hit' => $val, 'keys' => $used_keys, 'val' => $val);
}
return $res_arr ? $res_arr : false;
}
// I.e.:
$haystack[754] = "Norwegian";
$haystack[28]['details']['Norway'] = "Oslo";
$needle = "Norw";
if($results = array_search_ext($haystack, $needle, false))
foreach($results as $res)
echo "Found '$needle' in $res[type] '$res[hit]', using key(s) '".implode("', '", $res['keys'])."'. (Value: $res[val])<br />\n";
/* Printed result will be:
Found 'Norw' in val 'Norwegian', using key(s) '754'. (Value: Norwegian)
Found 'Norw' in key 'Norway', using key(s) '28', 'details', 'Norway'. (Value: Oslo)
*/
?>
mark dot php at mhudson dot net
12-Sep-2006 12:49
I was going to complain bitterly about array_search() using zero-based indexes, but then I realized I should be using in_array() instead.
// if ( isset( $_GET['table'] ) and array_search( $_GET['table'], $valid_tables) ) { // BAD: fails on first[0] element
// if ( isset( $_GET['table'] ) and ( FALSE !== array_search( $_GET['table'], $valid_tables) ) ) { OK: but wasteful and convoluted
if ( isset( $_GET['table'] ) and in_array( $_GET['table'], $valid_tables) ) { // BETTER
The essence is this: if you really want to know the location of an element in an array, then use array_search, else if you only want to know whether that element exists, then use in_array()
ob at babcom dot biz
28-Aug-2006 09:55
This function is based on the function in comment "array_search" from July 26th 2006.
I added the possibility of defining the key which $Needle shall be searched for.
<?php
// search haystack for needle and return an array of the key path,
// FALSE otherwise.
// if NeedleKey is given, return only for this key
// mixed ArraySearchRecursive(mixed Needle,array Haystack
// [,NeedleKey[,bool Strict[,array Path]]])
function ArraySearchRecursive($Needle,$Haystack,$NeedleKey="",
$Strict=false,$Path=array()) {
if(!is_array($Haystack))
return false;
foreach($Haystack as $Key => $Val) {
if(is_array($Val)&&
$SubPath=ArraySearchRecursive($Needle,$Val,$NeedleKey,
$Strict,$Path)) {
$Path=array_merge($Path,Array($Key),$SubPath);
return $Path;
}
elseif((!$Strict&&$Val==$Needle&&
$Key==(strlen($NeedleKey)>0?$NeedleKey:$Key))||
($Strict&&$Val===$Needle&&
$Key==(strlen($NeedleKey)>0?$NeedleKey:$Key))) {
$Path[]=$Key;
return $Path;
}
}
return false;
}
?>
Remove unnecessary new lines. I had to add them because of too long lines.
26-Jul-2006 02:19
/**
* Searches haystack for needle and returns an array of the key path if it is found in the (multidimensional) array, FALSE otherwise.
*
* mixed array_searchRecursive ( mixed needle, array haystack [, bool strict[, array path]] )
*/
function array_searchRecursive( $needle, $haystack, $strict=false, $path=array() )
{
if( !is_array($haystack) ) {
return false;
}
foreach( $haystack as $key => $val ) {
if( is_array($val) && $subPath = array_searchRecursive($needle, $val, $strict, $path) ) {
$path = array_merge($path, array($key), $subPath);
return $path;
} elseif( (!$strict && $val == $needle) || ($strict && $val === $needle) ) {
$path[] = $key;
return $path;
}
}
return false;
}
gullevek at gullevek dot org
19-Apr-2006 05:31
There were two previous entries for having a recursive search. The first one only searched for values, second one for values with an optional key.
But both of those stopped after they found an entry. I needed, that it searches recursive, with optional key and returns me all matches found in the array.
So I wrote this function:
needle is the value you search, haystack is the array of course, key is the optional key in the array where the needle should be. path should be never set on intial call. its an internal used variable.
It returns an array $path with the array entry 'found' where you can find all found groups. In these groups you have the array which holds the keys to find the data.
I hope this helps some of you.
<?php
function array_search_recursive_all($needle, $haystack, $key, $path = NULL)
{
if (!$path['level'])
$path['level'] = 0;
if (!$path['work'])
$path['work'] = array();
if (!is_array($haystack))
$haystack = array();
// go through the array,
foreach ($haystack as $_key => $_value)
{
// only value matches
if (is_scalar($_value) && $_value == $needle && !$key)
{
$path['work'][$path['level']] = $_key;
$path['found'][] = $path['work'];
}
// key and value matches
elseif (is_scalar($_value) && $_value == $needle && $_key == $key)
{
$path['work'][$path['level']] = $_key;
$path['found'][] = $path['work'];
}
elseif (is_array($_value))
{
// add position to working
$path['work'][$path['level']] = $_key;
// we will up a level
$path['level'] += 1;
// call recursive
$path = array_search_recursive_all($needle, $_value, $key, $path);
}
}
// cut all that is >= level
array_splice($path['work'], $path['level']);
// step back a level
$path['level'] -= 1;
return $path;
}
?>
If you call it with this:
<?
$right_side = array ('foo' => 'alpha', 'bar' => 'beta', 'delta' => 'gamma', 'gamma' => 'delta');
$value = 'beta';
$key = 'bar';
$pos = array_search_recursive_all($value, $right_side, $key);
?>
You will find in $pos this data
<?
Array
(
[level] => -1
[work] => Array
(
)
[found] => Array
(
[0] => Array
(
[0] => bar
)
)
)
?>
RichGC
20-Mar-2006 01:54
To expand on previous comments, here are some examples of
where using array_search within an IF statement can go
wrong when you want to use the array key thats returned.
Take the following two arrays you wish to search:
<?php
$fruit_array = array("apple", "pear", "orange");
$fruit_array = array("a" => "apple", "b" => "pear", "c" => "orange");
if ($i = array_search("apple", $fruit_array))
//PROBLEM: the first array returns a key of 0 and IF treats it as FALSE
if (is_numeric($i = array_search("apple", $fruit_array)))
//PROBLEM: works on numeric keys of the first array but fails on the second
if ($i = is_numeric(array_search("apple", $fruit_array)))
//PROBLEM: using the above in the wrong order causes $i to always equal 1
if ($i = array_search("apple", $fruit_array) !== FALSE)
//PROBLEM: explicit with no extra brackets causes $i to always equal 1
if (($i = array_search("apple", $fruit_array)) !== FALSE)
//YES: works on both arrays returning their keys
?>
congaz at yahoo dot dk
10-Mar-2006 03:38
Search a multi-dimensional array on keys!
-------------------------------------------
I needed to search dynamically in a multi-dimen array on keys. I came up with this little neat function. It is so amazingly simple, that I actually didn't think it would work - but it does...
mixed array_searchMultiOnKeys(array, array);
<?php
function array_searchMultiOnKeys($multiArray, $searchKeysArray) {
// Iterate through searchKeys, making $multiArray smaller and smaller.
foreach ($searchKeysArray as $keySearch) {
$multiArray = $multiArray[$keySearch];
$result = $multiArray;
}
// Check $result.
if (is_array($multiArray)) {
// An array was found at the end of the search. Return true.
$result = true;
}
else if ($result == '') {
// There was nothing found at the end of the search. Return false.
$result = false;
}
return $result;
// End of function,
}
// --- Test array_searchMultiOnKeys ---
$multiArray['webpages']['downloads']['music'] = 1;
$multiArray['webpages']['downloads']['pressmaterial'] = 5;
$multiArray['webpages']['links'] = 7;
array_searchMultiOnKeys($multiArray, array('webpages', 'links')); // returns 7.
array_searchMultiOnKeys($multiArray, array('webpages', 'downloads')); // returns true.
array_searchMultiOnKeys($multiArray, array('webpages', 'downloads', 'software')); // returns false.
?>
$multiArray / $searchKeysArray can be any size.
Happy hacking...
chappy at citromail dot hu
11-Feb-2006 08:26
If you're searching for strings and you need a case-insensetive script, there's one:
function array_lsearch($str,$array){
$found=array();
foreach($array as $k=>$v){
if(strtolower($v)==strtolower($str)){
$found[]=$v;
}
}
$f=count($found);
if($f===0)return false;elseif($f===1)return $found[0];else return $found;
}
It returns the original string, not the lower. Also good if use strtoupper().
hansen{}cointel.de
09-Feb-2006 02:26
may be good to take note of PHP's mind-boggling 'fuzzy' (vulgo "magic type-casting") comparison features not only in using the results, but also in the search, too:
<?php
$a=array("a","b",0,"c","d");
echo "a: ".array_search("a",$a);
echo "b: ".array_search("b",$a);
echo "c: ".array_search("c",$a);
echo "d: ".array_search("d",$a);
echo "0: ".array_search("0",$a);
echo "x: ".array_search("x",$a);
echo "1: ".array_search("1",$a);
?>
will result in:
a: 0, b: 1, c: 2, d: 2, 0: 2, x: 2, 1: false
as from "c" on, the first match found in $a is "0", as any string compared to an int is automatically cast to (int)0.
ludvig dot ericson at gmail dot com
08-Feb-2006 08:18
In response to the post beneath,
<?php
if ($userID = array_search($whatever, $array) !== false) {
}
?>
will also work, since it will be tested for explicitly NOT being a boolean false afterwards.
chrisAdams at 407x dot com
25-Jan-2006 09:32
This has been noted but took me a while to figure out: When the array that you are searching starts with position '0' array_search returns '0' for a match - evaluating as FALSE:
$usernameArray[0]='moe';
$usernameArray[1]='larry';
$usernameArray[2]='curly';
$username='moe';
// broken
if ($userNameArrayPosition=array_search($username, $usernameArray))
{ // even though the expression is true, will eval as false
echo 'userNameArrayPosition -'.$userNameArrayPosition;
}else{
echo 'evaluates false - userNameArrayPosition = -'.$userNameArrayPosition;
}
// will echo 'evaluates false - userNameArrayPosition = - 0'
// works
if (is_numeric($userNameArrayPosition=array_search($username, $usernameArray))
{ // will be true for all numeric values, but not bool. false
echo 'userNameArrayPosition -'.$userNameArrayPosition;
}else{
echo 'evaluates false - userNameArrayPosition = -'.$userNameArrayPosition;
}
// will echo 'userNameArrayPosition - 0'
$username='homer';
if (is_numeric($userNameArrayPosition=array_search($username, $usernameArray))
{ // will be true for all numeric values, but not bool. false
echo 'userNameArrayPosition -'.$userNameArrayPosition;
}else{
echo 'evaluates false - userNameArrayPosition = -'.$userNameArrayPosition;
}
// will echo 'evaluates false - userNameArrayPosition = - FALSE'
chrisAdams at 407x dot com
25-Jan-2006 08:53
This has been noted but took me a while to figure out: When the array that you are searching starts with position '0' array_search returns '0' for a match - evaluating as FALSE:
$usernameArray[0]='moe';
$usernameArray[1]='larry';
$usernameArray[2]='curly';
$username='moe';
// broken
if ($userNameArrayPosition=array_search($username, $usernameArray))
{ // even though the expression is true, will eval as false
echo 'userNameArrayPosition -'.$userNameArrayPosition;
}else{
echo 'evaluates false - userNameArrayPosition = -'.$userNameArrayPosition;
}
// will echo 'evaluates false - userNameArrayPosition = - 0'
// works
if (is_numeric($userNameArrayPosition=array_search($username, $usernameArray)==TRUE)
{ // will be true for all numeric values, but not bool. false
echo 'userNameArrayPosition -'.$userNameArrayPosition;
}else{
echo 'evaluates false - userNameArrayPosition = -'.$userNameArrayPosition;
}
// will echo 'userNameArrayPosition - 0'
$username='homer';
if (is_numeric($userNameArrayPosition=array_search($username, $usernameArray)==TRUE)
{ // will be true for all numeric values, but not bool. false
echo 'userNameArrayPosition -'.$userNameArrayPosition;
}else{
echo 'evaluates false - userNameArrayPosition = -'.$userNameArrayPosition;
}
// will echo 'evaluates false - userNameArrayPosition = - FALSE'
chernyshevsky at hotmail dot com
08-Jan-2006 01:53
array_search() in PHP 5 supports objects as needles whereas PHP 4 doesn't. The documentation should be updated to reflect this.
ludwig_von_rocht at yahoo dot com
23-Nov-2005 11:50
Here's a little function I wrote to find the key of the LAST occurrance of something in an array.
<?php
if(!function_exists('array_rsearch')){
function array_rsearch($search, $array, $strict = false){
$array = array_reverse($array, true);
foreach($array as $key => $value){
if($strict){
if($value === $search)
return $key;
} else {
if(strpos($value, $search))
return $key;
}
}
return false;
}
}
?>
mark meves
22-Nov-2005 11:13
A quick-and-dirty array_search_all() that i used for a small
dup-checking routine.
there are many, many ways to do something like this, not
the worst of which would be to use a relational database
for a dataset any larger than this ;)
-mark meves
<?php
/**
@return array of zero or more keys form $aHaystack whose
values match $mScalarNeedle using a
'==', (ie not strict) comparison
*/
function array_search_all($mScalarNeedle,$aHaystack){
return array_keys( array_filter($aHaystack,
create_function('$v','return $v == \''.addslashes($mScalarNeedle).'\';')
));
}
/*
test it:
*/
$aNicknames = array('jimmy'=>1,'james'=>1,'jim'=>1,
'billy'=>2,'william'=>2,'bill'=>2);
foreach(array('jim','bill') as $sName){
echo "variations for \"$sName\" :(".
implode(', ', array_search_all($aNicknames[$sName],$aNicknames)).
")\n";
}
/* outputs:
variations for "jim" are (jimmy, james, jim)
variations for "bill" are (billy, william, bill)
*/
?>
johnjc-phpdocs at publicinfo dot net
01-Nov-2005 06:37
The === and !== are not fully documented in either the Comparison Operator, Booleans type sections. They are talked about a bit more in the sections on strpos() and array_search() but those sections refer you to the section on Booleans for further information.
I am putting my contribution on === and !== in the Booleans section with pointers to it from the comment areas of other sections.
http://uk.php.net/manual/en/language.types.boolean.php
hakkierulez at nospamas dot hotmail dot nospam dot com
26-Oct-2005 01:36
If you simply want check if the search string is found, do this: (since the array number 0 evaluates as FALSE)
<?php
if (array_search($needle, $array)!== FALSE) {
//code goes here (
}
?>
arborrow at jesuits dot net
25-Sep-2005 08:26
I stumbled across some unexpected behavior with the array_search function. With a little help from the DallasPHPUsersGroup, I was able to trace it down to an array that I had attempted to start with a zero. The zero must be enclosed on single quote marks for the search function to work. Below are various syntaxes used to demonstrate the behavior. I hope this helps someone figure out why array_search is not working. Peace - Anthony
<?php
echo "<html><body>Let's try to search these arrays.<br><br>";
$findthis = "Assignments";
// syntax 1
$arcat1[] = 0; //comment out this line to test
//$arcat1[] = '0'; //uncomment this line to test
$arcat1[] = "Tests";
$arcat1[] = $findthis;
$arcat1[] = "Quizzes";
$arcat1[] = "Participation";
$arcat1[] = 0;
// the following search will not return the key if $arcat[] = 0;
// it will return the if $arcat[] = '0'; interestingly enough it will also work if $arcat = 1;
$keyresult = array_search ($findthis, $arcat1);
print_r($arcat1);
echo "<br>Arcat1 Key:".$keyresult."<br><br>";
//syntax 2
$arcat2 = array(0=>0, 1=>"Tests", 2=>"Quizzes", 3=>"Participation", 4=>"Assignments"); //comment out this line to test
//$arcat2 = array(0=>'0', 1=>"Tests", 2=>"Quizzes", 3=>"Participation", 4=>"Assignments"); //uncomment this line to test
// the following search will not return the key if $arcat2 = array(0=>0 ...);
// it will return the key if $arcat2 = array(0=>'0' ...);
$keyresult = array_search($findthis, $arcat2);
print_r($arcat2);
echo "<br>Arcat2 Key: ".$keyresult."<br><br>";
//syntax 3
$arcat3 = array(0); //comment out this line to test
//$arcat3 = array('0'); //uncomment this line to test
array_push($arcat3, $findthis);
array_push($arcat3, "Tests");
array_push($arcat3, "Participation");
array_push($arcat3, "Quizzes");
// the following search will not return the key if $arcat3 = array(0);
// it will return the key if $arcat3 = array('0'); interestingly enough it will also work if $arcat3 = array(1);
$keyresult = array_search($findthis, $arcat3);
print_r($arcat3);
echo "<br>Arcat3 Key: ".$keyresult."<br><br>";
?>
ludvig dot ericson at gmail dot com
06-Sep-2005 07:08
To the reply below,
note that you can compare an array with another array using == and ===
05-Aug-2005 12:57
If you give a delimiter (or "glue") to implode() this because a little more robust.
To use previous example with slight modification:
$array2search = array("pat","ter","n");
$string = implode('|', $array2search); // now "pat|ter|n"
if (strpos($string, "pattern" ) !== false) {
// wont get here
}
Now, obviously if you search for strpos($string, "pat|ter|n"), you're going to have problems again... But using a delimiter like this should help avoid most if not all "unforseen" cases.
benoit at bh-services (dot) com
18-Jun-2005 06:44
In answer to "info" at jake the spud dot com
This code doesn't work in all cases and may have unexpected results.
For example, it you have this code:
$array2search = array("pat","ter", "n");
if( strpos( implode( "", $array2search), "pattern" ) > -1 )
{
// You will be there ... but "pattern" does not exist in the array ...
// something is wrong !
}
There is no real solution using this code even if you try to enclose your elements by a special char ... because the special char could be part of the pattern.
If it works for you, it won't work in all cases.
/benoit
"info" at jake the spud dot com
03-Jun-2005 05:31
If you don't need the power of recursive functions, and you want to just search within an array for the existence of a string pattern, you can always try this:
if( strpos( implode( "", $array2search), "pattern" ) > -1 )
{
// code to execute here
}
It's kind of lame and childish, but gets the job done in a pinch.
Forgive me if someone else suggested this previously. I was racking my brain trying to do this using array_search(), in_array() and the like, and all I wanted was something dead simple.
kmkz [AT] kmkz [DOT] com
07-May-2005 02:46
I always wanted an array_replace function that could search and replace within an array, so I made one (its kinda simple and a bit inefficient, but c'est la vie):
<?php
function array_replace($search, $replace, &$array) {
foreach($array as $key => $value) {
if($value == $search) {
$array[$key] = $replace;
}
}
}
?>
vlad dot gladin at 102mg dot ro
05-Apr-2005 10:33
I found this useful especially for parsing htmls from
$file=file("http://a.website.com/htmlpage.html");
function array_search_extended($file,$str_search)
{
foreach($file as $line)
{
if (strpos($line, $str_search)!== FALSE)
{
return $line;
}
}
return false;
}
hanafi at pixella dot com
21-Jan-2005 12:37
If you want to search in a multi-dimensional array and just a portion, not the whole value, try this.
<?
$Projects[0] = array(123, "Text 1");
$Projects[1] = array(456, "Text 2");
$Projects[2] = array(789, "Text 3");
$search_value = "ext 2";
foreach ($Projects as $key => $row)
{
foreach($row as $cell)
{
if (strpos($cell, $search_value) !== FALSE)
{
echo "<p>".$key;
}
}
}
?>
Swoog DOT News A@T LaPoste DOT NET_DELME
17-Jan-2005 04:48
[[Excuse me but the return line of the precedent fuction had an error :( :( :( ]]
Just For Say I Had Reworked the function Object_Search in Object_Search_All :
<?php
function object_search_all(&$needle, &$haystack, $strict=false) {
$results = array();
if(!is_array($haystack)) return NULL;
foreach($haystack as $k => $v) {
if(($strict && $needle===$v) || (!$strict && $needle==$v)) $results[] = $k;
}
return $results == array() ? false : $results;
}
?>
it's return _NULL_ if $haystack isn't an array;
it's retrun _false_ if there is no $needle in haystack
it work also with not numerics array (thanks to a _foreach_ )
Be Happy ;) ! :D
Bye !
Swoog DOT News A@T LaPoste DOT NET_DELME
17-Jan-2005 04:29
for "voituk on asg dot kiev dot ua" :
no need to do :
(get_class($needle)==get_class($haystack[$i])) && ($needle==$haystack[$i])
for type sensible searches, Because, in PHP, two objects are equals if and only if they have same class and all of their attributes are the same (values).
But Because of the untyping of PHP, same attributes can be == but not === so, to avoid problems with type sensible searches, do :
$needle===$haystack[$i]
Is Better ! ;)
stew at initiative dot uk dot com(stewart boutcher)
05-Jan-2005 03:54
Not to labour the point too much, but here's another, slightly less verbose multi dimensional recursive function...
function array_key_exists_recursive($needle,$haystack) {
foreach($haystack as $key=>$val) {
if(is_array($val)) { if(array_key_exists_recursive($needle,$val)) return 1; }
elseif($val == $needle) return 1;
}
return 0;
}
pornsak at neowin dot net
21-Nov-2004 03:28
This is a modified version of Mark Meves's wonderful function. I needed something that would be able to let me force search the key name where the needle should be found.
<?php
function array_search_recursive($needle, $haystack, $key_lookin="") {
$path = NULL;
if (!empty($key_lookin) && array_key_exists($key_lookin, $haystack) && $needle === $haystack[$key_lookin]) {
$path[] = $key_lookin;
} else {
foreach($haystack as $key => $val) {
if (is_scalar($val) && $val === $needle && empty($key_lookin)) {
$path[] = $key;
break;
}
elseif (is_array($val) && $path = array_search_recursive($needle, $val, $key_lookin)) {
array_unshift($path, $key);
break;
}
}
}
return $path;
}
?>
scripts at webfire dot org
03-Nov-2004 05:13
* Multi-Dimensional Array Search *
If you're searching for a function to search in Multi-Arrays,
this is probably usefull for you.
-------------------------------------------------------------
<?php
function multi_array_search($search_value, $the_array)
{
if (is_array($the_array))
{
foreach ($the_array as $key => $value)
{
$result = multi_array_search($search_value, $value);
if (is_array($result))
{
$return = $result;
array_unshift($return, $key);
return $return;
}
elseif ($result == true)
{
$return[] = $key;
return $return;
}
}
return false;
}
else
{
if ($search_value == $the_array)
{
return true;
}
else return false;
}
}
?>
-------------------------------------------------------------
It will return an Array with the keys from the original array
where your search-string was found or false. e.g.:
-------------------------------------------------------------
<?php
$foo[1]['a']['xx'] = 'bar 1';
$foo[1]['b']['xx'] = 'bar 2';
$foo[2]['a']['bb'] = 'bar 3';
$foo[2]['a']['yy'] = 'bar 4';
$foo['info'][1] = 'bar 5';
$result = multi_array_search('bar 3', $foo);
print_r($result);
?>
-------------------------------------------------------------
Output:
Array
(
[0] => 2
[1] => a
[2] => bb
)
-------------------------------------------------------------
I hope you like it ;)
greetz Udo
Flix Cloutier <felixcca at yahoo dot ca>
22-Oct-2004 12:01
There is no function to count the occurences of needle in haystack, so I made my own one...
<?php
function array_match($needle, $haystack)
{
if( !is_array($haystack) ) return false;
$i = 0;
while( (in_array( $needle, $haystack )) != FALSE )
{
$i++;
$haystack[array_search($needle, $haystack)] = md5($needle);
reset($haystack);
}
return $i;
}
?>
I know it's a bit crappy, but don't ask me too much, I'm still only 13... ;)
voituk on asg dot kiev dot ua
29-Sep-2004 12:04
There is no way to use this function to search an object in the array.
I want to suggest my own function for this problem solve
<?php
/** $Id$
* Searches the array for a given object and returns the corresponding key if successful or FALSE otherwise
*/
function object_search($needle, $haystack, $strict=false) {
if (!is_array($haystack)) return false;
for ($i=0; $i<count($haystack); ++$i) {
if ($strict) {
// STRICT
if ((get_class($needle)==get_class($haystack[$i])) && ($needle==$haystack[$i])) return $i;
} else {
// NO STRICT
if ($needle==$haystack[$i]) return $i;
}
}
return false;
}// function object_search
?>
leaetherstrip ATNOSPAM inbox DOT ru
28-Sep-2004 01:07
For get dennis dot decoene 's binary_search working on arrays with 1 or 2 elements, just replace
<?php
while ($high - $low > 1){
?>
with
<?
while ($high - $low >= 1){
?>
Wouter van Vliet <me |