Handy functions

Published 19 February, 2007 in Programming - 0 Comments

How many times don’t you write code like this: $var = isset($_GET['var']) ? $_GET['var'] : 'default';? I read an article in Linux Format (the paper issue) about the up and comming PHP6 (well, it will probably take some time until it gets stable but you can already download it) and some of its new functions and stuff and learned that there will be a function called $var = isset($_GET['var']) ? $_GET['var'] : 'default';. This function will work like this:
$var = isset($_GET['var']) ? $_GET['var'] : 'default';. Pretty much nicer than the old way!

So I though: How hard can it be to implement the same kind of functionality in a user defined function. Well, it’s not hard att all, and here’s how simple it is:

22 lines of PHP
  1. /**
  2. * issetor
  3. *
  4. * @param mixed &$what Assoc array key
  5. * @param mixed $else Default value
  6. * @return mixed
  7. */
  8. function issetor(&$what, $else)
  9. {
  10. return isset($what) ? $what : $else;
  11. }
  12. #=================================================
  13. $arr = array(‘key1’ => ‘value1’, ‘key2’ => 1);
  14. $var1 = issetor($arr[‘key1’], ‘some value’);
  15. echo $var1; # will echo: value1
  16. $var2 = issetor($arr[‘key5’], ‘default for key 5’);
  17. # will echo: default for key 5
  18. echo $var2;

The only thing noticable here is that the first argument needs to be passed by reference or PHP will throw a warning (depending on the error/warning level set).

Of cource you can escape this issue all together just by choking PHP errors/warnings – $var = isset($_GET['var']) ? $_GET['var'] : 'default'; – but that’s just pure ugly in my opinion.

Just by modifying the function above slightly we also get a nice way for writing:
$var = isset($_GET['var']) ? $_GET['var'] : 'default';

23 lines of PHP
  1. /**
  2. * isemptyor
  3. *
  4. * @param mixed &$what Assoc array key
  5. * @param mixed $else
  6. * @return mixed
  7. */
  8. function isemptyor(&$what, $else)
  9. {
  10. return empty($what) ? $else : $what;
  11. }
  12. #=================================================
  13. $var1 = “Hello”;
  14. $var2 = “”;
  15. $myvar = isemptyor($var1, ‘Default’);
  16. echo $myvar; # will echo: Hello
  17. $myvar = isemptyor($var2, ‘Default’);
  18. # will echo: Default
  19. echo $myvar;

And that’s it. I use them all the time!