$search_array = array('first' => 1, 'second' => 4);
代码如下 |
复制代码 |
$search_array = array('first' => null, 'second' => 4);
// returns false
isset($search_array['first']);
// returns true
array_key_exists('first', $search_array);
?>
|
if (array_key_exists('first', $search_array)) {
echo "The 'first' element is in the array";
}
?>
代码如下 |
复制代码 |
$a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse");
echo array_search("Dog",$a);
?>
$a=array("a"=>"5","b"=>5,"c"=>"5");
echo array_search(5,$a,true);
?>
上述代码将输出下面的结果:
b
|
Example #2 Comparison between array_key_exists() and isset()
isset() does not return TRUE for NULL values in the array, while array_key_exists() does.
The code is as follows
|
Copy code
|
$search_array = array('first' => null, 'second' => 4);
// returns false
isset($search_array['first']);
// returns true
array_key_exists('first', $search_array);
代码如下 |
复制代码 |
$result = array();
for($i = 501; $i < 600; $i++) {
if(!isset($arr[$i])) continue;
$result[] = $arr[$i];
}
|
?>
|
mixed array_search ( mixed $needle, array $haystack [, bool $strict] )
The first parameter is the value to be searched, the second parameter is the array, and the last parameter refers to whether to check whether the data types are the same when searching.
The code is as follows
|
Copy code
|
$a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse");
echo array_search("Dog",$a);
?>
$a=array("a"=>"5","b"=>5,"c"=>"5");
echo array_search(5,$a,true);
?>
The above code will output the following results:
b
From this point of view, when the amount of data is not large, such as less than 1,000, any search method can be used, and it will not become a bottleneck;
When the amount of data is relatively large, array_key_exists is more appropriate.
Of course, the memory occupied by array_key_exists here is relatively large. According to calculations
The array structures are: array(1, 2, 3, ..) and array(1 => true, 2 => false, ..)
Their memory usage ratio is 1:2;
Note: array_key_exist is more than ten or even dozens of times more efficient than in_array
A simple algorithm
Assume that the array has 1000 elements and the key values are unordered positive integers less than 1000000 and are not continuous, as follows
$arr = array(1 => 'sadas', 20 => 'aasd', 5002 => 'fghfg', 190023 => 'rty', 248 => 'kj', 76 = > 'sddd' ,...);
Now we want to get the elements whose key value in array $arr is greater than 500 and less than 600. Is there a more efficient algorithm without using foreach to completely loop?
Answer
The code is as follows
|
Copy code
|
$result = array();
for($i = 501; $i < 600; $i++) {
If(!isset($arr[$i])) continue;
$result[] = $arr[$i];
}
http://www.bkjia.com/PHPjc/628954.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/628954.htmlTechArticleThere are many ways to find the specified value in an array in php. Let me introduce the array search function in_array( in php ), array_key_exists(), array_search() usage to find whether an element is in an array...
|
|
|