"3DPixel have consistently provided exceptional levels of service and support to our rapidly expanding business"

Zapper.co.uk Matt WhiteCo-Founder

ifelse() - Output the first argument that exists Simon Stevens wrote this on 23 Mar, 2011

I wrote a tiny function many years ago that simplified echoing out variables into a form for me. It took 2 arguments and output the first variable if it was present, and the 2nd if not. I called it postOrNot(), and it was terrible.

I wrote a tiny function many years ago that simplified echoing out variables into a form for me. It took 2 arguments and output the first variable if it was present, and the 2nd if not. I called it postOrNot(), and it was terrible for 2 reasons:

  1. The function name was bad (now was that an uppercase O or an N?)
  2. It was too limited, sometimes I'd have to nest it

I addressed those issues in the function below. It has a simple, short and memorable function name and takes as many arguments as I needed.

function ifelse(){
	if(func_num_args() < 2) 
		trigger_error("ifelse() requires 2 or more arguements", E_USER_ERROR); 
	else { 
		$args = func_get_args();
		foreach($args as $arg){
			if(isset($arg)) return $arg;
		}
		return false; 
	}
}

It'll return out the first argument that is set or false if none of them.

Enjoy

Be the first to comment!

© Copyright 3DPixel Ltd. 2013
Company #04721309 | VAT: 876 4611 93

3DPixel Ltd.
Suite 12, 1-3 The Courtyard, Bolton, Lancashire, BL1 8PB