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

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


+ nine = fifteen

CommentLuv badge