phpeveryday.com

The best tutorial of php, php framework, php strategies, object oriented oriented,


PHP Array: Searching Arrays

Tag: array   Category: PHP Basic
post: 26 Mar 2008 read: 1,155


PHP Array Tips - Part 18: Do you want to search an array for a particular key or value? you can use array_key_exists() or in_array(). Like this:

Sample for searching value


<?php
$arr = array("zero","zero","zero","one", "two", "three", "four", "five", "six");

if(in_array("five",$arr)){
  echo "found";
}else{
  echo "not found";
}
// result found
?>

Sample for searching value and key


<?php
$arr = array("zero","zero","zero","one", "two", "three", "four", "five", "six");

function arraySearch($needle, $haystack){
  if(!is_array($haystack)) {
    die("second argument is not array");
  }
  
  foreach($haystack as $key => $val){
    if(preg_match("/$needle/i", $val) || preg_match("/$needle/i", $key)){
	  return true;
	  break;
	}
  }
}

if(arraySearch("zero", $arr)){
  echo "found";
}else{
  echo "not found";
}

if(arraySearch(4, $arr)){
  echo "found";
}else{
  echo "not found";
}

?>


Series this article:
PHP Array: Processing Array Use SPL
PHP Array: Processing Nested Array
PHP Array: Using SPL to Process Nested Array
PHP Array: Counting Number of Elements
PHP Array: Converting Strings to Arrays
PHP Array: Converting Arrays to Strings
PHP Array: Swapping Array keys and Values
PHP Array: Adding element to an Array
PHP Array: Taking an Element off the beginning of the array
PHP Array: Adding an Element to the Beginning of the Array
PHP Array: Taking an element off the end of the array
PHP Array: Adding or removing elements from the middle of an array
PHP Array: Extracting Contiguous Segments of an Array
PHP Array: Removing Duplicate Array Elements
PHP Array: Re-indexing Array
PHP Array: Randomizing Array
PHP Array: Searching Arrays
PHP Array: Searching Nested Array
PHP Array: Reversing Arrays
PHP Array: Filtering Array Elements
PHP Array: Sorting Arrays

| Give Your Opinion | Recommend
Share and Bookmark to: These icons link to social bookmarking sites where readers can share and discover new web pages.
digg del.icio.us technorati Ma.gnolia BlinkList

Recommended articles by other readers:
Web Services: How PHP Kiss VB.NET? (Part 1)
Chart: How to Build Cool Animation Real Time Chart
Joomla: Fast Road to Understand Component Programming
Email: Send Attachement Mail
mod_rewrite - Part 1: create your "fantasy" URL

What do You Think?
Your Name *:
Email *:
(Will not be published)
Website/URL:
Your Comment *:
* Required


619
posting