方法:1、使用in_array()函數(shù),可檢測數(shù)組中是否存在指定元素值,語法“in_array(元素值,數(shù)組)”;2、使用array_search()函數(shù),可在數(shù)組中搜索指定元素值,語法“array_search(元素值,數(shù)組)”。
本教程操作環(huán)境:windows7系統(tǒng)、PHP7.1版、DELL G3電腦
php中判斷一個(gè)元素有沒有在數(shù)組中
方法1:使用in_array()函數(shù)
in_array() 函數(shù)可以查找數(shù)組中是否包含某個(gè)值,如果存在則返回 TRUE,不存在則返回 FALSE。語法格式如下:
in_array($needle, $array[, $strict = FALSE])
參數(shù)說明如下:
- $needle:為待搜索的值,如果 $needle 是字符串,則在比較時(shí)區(qū)分大小寫;
- $array:為待搜索的數(shù)組;
- $strict:為可選參數(shù),默認(rèn)為 FALSE。
- 如果 $strict 為空或者 FALSE,則 in_array() 函數(shù)只會(huì)檢查 $needle 的值是否和 $array 中的值相等;
- 如果 $strict 的值為 TRUE,in_array() 函數(shù)除了會(huì)檢查 $needle 和 $array 中的值之外,還會(huì)比較它們的類型是否相等。
提示:in_array() 函數(shù)只適用于在一維數(shù)組中查找某個(gè)元素,不會(huì)遞歸查找數(shù)組中每個(gè)維度的元素。
示例:使用 in_array() 函數(shù)判斷數(shù)組中是否包含某個(gè)值
<?php header("Content-type:text/html;charset=utf-8"); $sites = array('a', 'b', '1', 2, 3); if (in_array("a", $sites)) { echo "指定元素在數(shù)組中"; } else { echo "指定元素不在數(shù)組中"; } ?>
2、使用array_search()函數(shù)
array_search() 函數(shù)在數(shù)組中搜索某個(gè)鍵值,并返回對(duì)應(yīng)的鍵名。
如果在數(shù)組中找到指定的鍵值,則返回對(duì)應(yīng)的鍵名,否則返回 FALSE。如果在數(shù)組中找到鍵值超過一次,則返回第一次找到的鍵值所匹配的鍵名。
該函數(shù)的語法格式如下:
array_search($needle, $haystack[, $strict = false])
參數(shù)說明如下:
- $needle:為要搜索的值,如果 $needle 為字符串類型,則在搜索時(shí)區(qū)分大小寫;
- $haystack:為一個(gè)數(shù)組;
- $strict:可選參數(shù),可以為空,默認(rèn)為 False。
- 如果 $strict 為 False,則 array_search() 在 $haystack 中搜索 $needle 時(shí)僅會(huì)比較值,不比較類型。
- 如果 $strict 為 True,則 array_search() 在 $haystack 中搜索 $needle 時(shí)會(huì)同時(shí)比較值和類型。
<?php header("Content-type:text/html;charset=utf-8"); $sites = array("a"=>"red","b"=>"green","c"=>"blue"); if (array_search("red",$sites)) { echo "指定元素在數(shù)組中"; } else { echo "指定元素不在數(shù)組中"; } echo "<br>指定元素的鍵名為:".array_search("red",$sites); ?> ?>
推薦學(xué)習(xí):《PHP視頻教程》