Function : Check if array index is set and whether it has a value.

0saves

Array Index Set

This function lets you determine whether an array index is set and whether it has a value. It takes array item, array and default value as parameters. If the element is empty it returns FALSE or whatever you specify as the default value.


<?php

/**
 * Array Index Set - Lets you determine whether an array index is set and whether it has a value.
 *
 * If the element is empty it returns FALSE (or whatever you specify as the default value.)
 * @param    string - $default
 * @param    array - $array
 * @param    mixed - $item
 * @return    mixed    depends on what the array contains
 */
if ( ! function_exists('element'))
{
 function element($item, $array, $default = FALSE)
 {
 if ( ! isset($array[$item]) OR $array[$item] == "")
 {
 return $default;
 }

 return $array[$item];
 }
}

?>

Usage :


<?php

$array = array("a"=>"apple", "b"=>"bat","c"=>"cat");

$x = element("a", $array); //returns apple

$x = element("x",$array); //returns false

$x = element("b",$array,"ball"); //returns ball

$x = element("n",$array,"Not Found"); //returns Not Found

?>
If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Related posts:

  1. PHP : Array Functions Tutorial – Part 3
  2. PHP : Array Functions Tutorial – Part 2
  3. PHP : Array Functions Tutorial – Part 1
  4. Function : Converts a MySQL Timestamp to Unix
  5. Function : Converts GMT time to a localized value
  6. Function : Converts a local Unix timestamp to GMT
  7. Function : Get number of days in month
  8. Function: Get Random Element from Array
  9. What is an Array? Functions of Array- Array Tutorials
  10. How to Get the Thumbnail of the First Image from the Post and Display it in WordPress

Related Posts

About the Author: Abhishek Sanghvi

Hi Friends, my name is Abhishek Sanghvi and I am the founder of this “open source script” site MYPHPSCRIPTZ. I have been learning and practising PHP from the last 3 years. You could always contact me if you wish to have some code for your need. I would surely try and solve them for you at abhishek(at)myphpscriptz(dot)com

1 Comment + Add Comment

Leave a comment


five + one =

CommentLuv badge