Home  >  Article  >  Backend Development  >  PHP搜索数组的实现方法介绍_PHP教程

PHP搜索数组的实现方法介绍_PHP教程

WBOY
WBOYOriginal
2016-07-15 13:33:16851browse

array_unshift() //在数组的头部添加元素,也就是把一个新的元素插入到数组,相应索引还自动改变
array_push() //在数组尾部添加元素
array_shift() //在数组头部删除元素
array_pop() //在数组尾部删除元素

这几个函数的用法基本差不多,在PHP的帮助手册中可以得到具体的用法,在此就不多啰嗦了。

PHP搜索数组的代码示例:

in_array()函数在数组中搜索一个特定的值,如果找到则返回TRUE,否则返回FALSE。以下的示例来自PHP帮助手册。

  1.  ?php  
  2. $os = array("Mac", "NT", "Irix", "Linux");  
  3. if (in_array("Irix", $os)) {  
  4. echo "Got Irix";  
  5. }  
  6. if (in_array("mac", $os)) {  
  7. echo "Got mac";  
  8. }  
  9. ?> 

要特别说明的,in_array()在搜索时是区分大小的,所以以上的例子只会返回“Got Irix”。你也可以用数组作为子串在数组中进行搜索,更多的实例请查看帮助手册。

PHP搜索数组之搜索关联数组

如果你搜索的数组是一个关联数组,就要使用array_key_exists(),其返回值跟in_array()一样。同样我们引用PHP帮助手册的例子来说明:

  1.  ?php  
  2. $search_array = array('first' => 1, 'second' => 4);  
  3. if (array_key_exists('first', $search_array)) {  
  4. echo "The 'first' element is in the array";  
  5. }  
  6. ?> 

相信这么一段代码就不要解释了吧,一看就能够明白,其结果:The ‘first’ element is in the array。这说明”first”存在于数组”search_array”中。


www.bkjia.comtruehttp://www.bkjia.com/PHPjc/446069.htmlTechArticlearray_unshift() //在数组的头部添加元素,也就是把一个新的元素插入到数组,相应索引还自动改变 array_push() //在数组尾部添加元素 array_shif...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn