|
Posted by Toby A Inkster on 03/27/07 10:36
Lo'oris wrote:
> $name=$_GET['name'];
> if (!$name)
> $name="value";
>
> i can't figure out how to shorten this thing. Is there some kind of
> operator i don't know about?
The current PHP method is:
$name = $_GET['name'] ? $_GET['name'] : 'value';
It was proposed that PHP 6 should have a new function "ifsetor" which
would achieve the same thing using this syntax:
$name = ifsetor($_GET['name'], 'value');
However, this proposal was rejected in favour for making the middle part
of the current method optional, so you could write:
$name = $_GET['name'] ? : 'value';
However, if you want to use the above, you'll need to wait for PHP 6, and
your code will not be backwards-compatible with earlier versions of PHP.
Personally, I've written my own ifsetor() function, and just use that.
/**
* Implementation of proposed (but discarded) PHP6 built-in function.
*
* @param mixed $value Preferred value.
* @param mixed $fallback Fallback value.
* @return mixed isset($value) ? $value : $fallback
*/
function ifsetor ($value, $fallback)
{
if (isset($value))
return $value;
return $fallback;
}
I use this most often for loading settings. Assuming I have a bunch of
settings from a file stored in some array:
$mode = ifsetor($settings['mode'], 3); // default mode is 3
--
Toby A Inkster BSc (Hons) ARCS
Contact Me ~ http://tobyinkster.co.uk/contact
Geek of ~ HTML/SQL/Perl/PHP/Python*/Apache/Linux
* = I'm getting there!
Navigation:
[Reply to this message]
|