php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #43236 "if set" and "if not set" functions (ifset, ifnset)
Submitted: 2007-11-10 20:32 UTC Modified: 2007-11-10 21:38 UTC
Votes:1
Avg. Score:5.0 ± 0.0
Reproduced:1 of 1 (100.0%)
Same Version:1 (100.0%)
Same OS:0 (0.0%)
From: zyss at mail dot zp dot ua Assigned:
Status: Not a bug Package: Feature/Change Request
PHP Version: 5.2.5 OS: All
Private report: No CVE-ID: None
 [2007-11-10 20:32 UTC] zyss at mail dot zp dot ua
Description:
------------
PHP programmers often need to check if certain variable is set when assigning its value to other variable or using it in expression. For example:

  $item_id = isset($_POST['item_id']) ? $_POST['item_id'] : null;

which is quite unreadable.

It would be much easier to write such things if there are function ifnset(mixed $value, mixed $alt) (If Not Set) which returns $value if $valus is set or $alt otherwise. Example above could be replaced with:

  $item_id = ifnset($_POST['item_id'], null);

or, if another function is added - ifset - which returns null if its argument is not set or not defined:

  $item_id = ifset($_POST['item_id']);

Similar function exists in MySQL (http://dev.mysql.com/doc/refman/5.1/en/control-flow-functions.html#function_ifnull) which makes life much easier when working with MySQL.

It is not possible to implement this function in PHP because when undefined or unset variable is passed as function argument PHP emits warning. Although warnings could be suppressed with @ it significantly slows down performance when such situation happens. Besides debugger catches all suppressed warnings anyway.

Thanks.


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2007-11-10 21:38 UTC] johannes@php.net
PHP 6 has the "?:" operator ($result = $foo ?: $bar;) which is close to your request and which will most likely be merged back to 5.3.
 [2012-09-16 14:24 UTC] jay-php at vengefulstapler dot com
johannes, I haven't had a chance to test out ?: yet but someone else said that 
$val = $var['foo'] ?: ''; would still throw a notice if $var['foo'] was not set.

If that is true, then it would still be nice to have something like what is 
described here.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Fri Mar 29 15:01:28 2024 UTC