Finding Items in an Array with PHP
Published 2 years, 6 months ago in Basics and PHPThe problem: we have an array of items in PHP and we want to find out if a specific item is in the array. In code we can define the array as:
// create an array of strings called $fruitBasket:
$fruitBasket = array( "Apple", "Orange", "Mango", "Lemon", "Pear" );
?>
IE we have an array called $fruitBasket which contains 5 strings, each of which is the name of a fruit. We want to find out if there is an Apple in the $fruitBasket - is there an element "Apple" in the array?
We do this with the following code:
This code uses the in_array() method to check if the element "Apple" exists in the array $fruitBasket:
in_array("Apple", $fruitBasket)
in_array() takes two parameters here: firstly the object we're looking for, in this case "Apple", and secondly the array which we're looking in, $fruitBasket. It then returns a boolean value: true if "Apple" is in the array, or false if it isn't.
References: php.net manual: in_array() function
If you have a low-traffic website, consider joining the Money4Banners advertising network. They will pay you £10 + £5 each month for displaying a small advert on three of your pages, regardless of traffic. American webmasters are welcome, and since £10 == $20, you make more!
Search
Categories
- ASP (3)
- ASP Basics (3)
- Blogs (2)
- C# (1)
- Firefox (1)
- Flash (1)
- Google (6)
- Hacks (3)
- Java (1)
- PHP (12)
- Basics (8)
- Files (1)
- Image Handling (3)
- Puzzles (1)
- Ruby (1)
- Tips (10)
- Web Hosting (3)
- Web Hosting Articles (1)
- Web Hosting News (2)
- Windows (6)
- Wordpress (2)
Related Entries
- PHP
- Reading a file's contents with PHP
- Find a visitor's IP Address with PHP
- How to Find the Current URL with PHP
- Save Embedded Media and Other Files in Firefox
- How to use the query string in PHP
- How to use PHP in pages with a .html extension (or any other)
- Generating Random Numbers in PHP
- The Difference Between require() and include()
- Write text on a dynamically generated image using PHP
No Responses to “Finding Items in an Array with PHP”
Please Wait
Leave a Reply
You must log in to post a comment.