I have an interesting situation. I am using a form that is included on multiple pages (for simplicity and to reduce duplication) and this form in some areas is populated with values from a DB. However, not all of these values will always be present. For instance, I could be doing something to the effect of:
<?php echo set_value('first_name', $first_name); ?>
and this would work fine where the values exist, but $user is not always set, since they may be typing their name in for the first time. Yes you can do isset($first_name) && $first_name inside an if statement (shorthand or regular)
I am trying to write a helper function to check if a variable isset and if it's not null. I would ideally like to do something like varIsset('first_name'), where first_name is an actual variable name $first_name and the function would take in the string, turn it into the intended variable $first_name and check if it's set and not null. If it passes the requirements, then return that variables value (in this case 'test'). If it doesn't pass the requirements, meaining it's not set or is null, then the function would return '{blank}'.
I am using CodeIgniter if that helps, will be switching to Laravel in the somewhat near future. Any help is appreciated. Here is what I've put together so far, but to no avail.
function varIsset($var = '')
{
foreach (get_defined_vars() as $val) {
if ($val == $var) {
if (isset($val) && $val) {
echo $val;
}
break;
}
}
die;
}
Here is an example usage:
<?php
if (varIsset('user_id') == 100) {
// do something
}
?>
I would use arrays and check for array keys myself (or initialize all my variables...), but for your function you could use something like:
function varIsset($var)
{
global $$var;
return isset($$var) && !empty($$var);
}
Check out the manual on variable variables. You need to use global $$var; to get around the scope problem, so it's a bit of a nasty solution. See a working example here.
Edit: If you need the value returned, you could do something like:
function valueVar($var)
{
global $$var;
return (isset($$var) && !empty($$var)) ? $$var : NULL;
}
But to be honest, using variables like that when they might or might not exist seems a bit wrong to me.
It would be a better approach to introduce a context in which you want to search, e.g.:
function varIsset($name, array $context)
{
return !empty($context[$name]);
}
The context is then populated with your database results before rendering takes place. Btw, empty() has a small caveat with the string value "0"; in those cases it might be a better approach to use this logic:
return isset($context[$name]) && strlen($name);
Try:
<?php
function varIsset($string){
global $$string;
return empty($$string) ? 0 : 1;
}
$what = 'good';
echo 'what:'.varIsset('what').'; now:'.varIsset('now');
?>
Related
My problem is that I have lots of functions with VERY long lists of function parameters such as this one:
function select_items($con,$type,$id_item,$item_timestamp,$item_source_url,$item_type,$item_status,$item_blogged_status,$item_viewcount,$item_language,$item_difficulty,$item_sharecount,$item_pincount,$item_commentcount,$item_mainpage,$item_image_width,$item_image_height,$item_image_color,$item_modtime,$order,$start,$limit,$keyword,$language,$id_author,$id_sub_category,$id_category,$id_tag,$id_user){ ... }
As you can see its super long and (of course) very hard to maintain. Sometimes I need all of the variables to construct a super complex sql query, but sometimes I just use 1 or 2 of them. Is there a way to avoid this colossal list of parameters? For example with some strict / special naming convention ?
So basically I need something like this:
$strictly_the_same_param_name="It's working!";
echo hello($strictly_the_same_param_name);
function hello() //<- no, or flexible list of variables
{
return $strictly_the_same_param_name; // but still able to recognize the incoming value
}
// outputs: It's working!
I thought about using $_GLOBALs / global or $_SESSIONs to solve this problem but it doesn't seems really professional to me. Or is it?
For a first step, as you said, sometimes you need to call the function with only 2 args, you can set default values to your arguments in the declaration of your function. This will allow you to call your function with only 2 args out of 25.
For example:
function foo($mandatory_arg1, $optional_arg = null, $opt_arg2 = "blog_post") {
// do something
}
In a second step, you can use, and especially for that case, arrays, it will be way more simple:
function foo(Array $params) {
// then here test your keys / values
}
In a third step, you can also use Variable-length argument lists (search in the page "..."):
function sum(...$numbers) {
$acc = 0;
foreach ($numbers as $n) {
$acc += $n;
}
return $acc;
}
But ultimately, I think you should use objects to handle such things ;)
You can try use ... token:
$strictly_the_same_param_name= ["It's working!"];
echo hello($strictly_the_same_param_name);
function hello(...$args) //<- no, or flexible list of variables
{
if ( is_array( $args ) {
$key = array_search( 'What you need', $args );
if ( $key !== false ) {
return $args[$key];
}
}
return 'Default value or something else';
}
So, I am writing a function that receives two arguments, and before I do anything with these variables, I want to check if they are not null.
if (!is_null($foo) && !is_null($bar)) {
/* do something */
}
The problem is that I think we are repeating code, and in some cases when the variable name is a little bit bigger, it becomes painful to write every time.
So, there is a way to shorten this code?
You can use isset which returns FALSE if variable is null. You can set there a lot of variables so code will be shorter:
if (isset($foo, $bar))
You can write your own function to check this:
function is_any_null() {
$params = func_get_args();
foreach($params as $param) {
if (is_null($param))
return true;
}
return false;
}
Now you can use it like this:
if (!is_any_null($foo, $bar)) {
/* do something */
}
is_null() checks a variable to determine if the value is NULL. It can be used in an if statement. It depends on what you would like to do in that if statement. For example, if you would like to do an echo, you can make it a bit shorter using the `elvis``operator:
echo (is_null($foo) && is_null($bar)) ?: 'The values are not null';
Or you could make it a one liner by leaving the { and } out of your code and putting everything on one line.
if (!is_null($foo) && !is_null($bar)) die("NULLLLL");
if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
OR
if((!empty($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
OR just
if($_GET['example']=='somevalue'){ ... }
I am asking that why I have seen many example where people check first if $_GET['example'] is set and then if $_GET['example']=='somevalue' ( first and second example above ).
I don't understand why not just use the last solution ( if $_GET['example']=='somevalue' then $_GET['example'] is obviously set ).
This question refers to any other variable ( $_POST, $_SERVER, ecc ).
if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
Is the right one, you want to know that the "variable" exists (or is set) in order to use it. Empty just checks wether it has data of any kind or not.
For example:
<?php
$foo= 0;
if (empty($foo)) { // True because $foo is empty
echo '$foo is either 0, empty, or not set at all';
}
if (isset($foo)) { // True because $foo is set
echo '$foo is set even though it is empty';
}
if (isset($var)) { // FALSE because $var was not declared before
...
}
?>
The differences between isset and empty are subtle but important. They are most relevant when used alone. If you are checking that a variable exists and is a truethy value (e.g. any string that is not all spaces or 0s) you can use either interchangeably.
When to use isset
Use isset when it's important to know if the variable has been defined and is not null:
if (isset($maybeExistsMaybeNull)) {
// variable defined and is not NULL
}
When to use !empty
Use !empty when it's important to know if the variable has be defined and is truthy
if (!empty($mightBeEmpty)) {
// variable defined, and isn't "", " ", 0, "0" etc.
}
!empty is a great shorthand for exists and is something.
When to use array_key_exists
Use array_key_exists when it's important to know if the key exists and the value is of no importance:
if (array_key_exists('something', $array)) {
// $array['something'] exists, could be literally anything including null
}
When not to use isset
If your code looks like this:
if (isset($something) && $something) {
// code is shorter with !empty
}
When not to use !empty
If your code looks like this:
if (!empty($something) && $something === "") {
// you meant isset. this is unreachable.
}
Then you're writing code that can't be executed
Code that throws errors is error prone
Avoid writing code that issues notices/warnings that you are ignoring. For example in the question:
if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
The first use of example is an undeclared constant. Or is it undeclared - what if you've got define('example', "foo"); somewhere else in the code.
if($_GET['example']=='somevalue'){ ... }
If the url doesn't contain ?example=.. that's going to issue a notice too.
Writing code without displaying errors means you can very easily miss mistakes like the first.
In context: isset and !empty are equivalent
For the example given, these two language constructs act exactly the same.
There is no case where one will act differently than the other, neither will issue a notice if the variable is undefined, and no measurable difference in performance between the two.
As others have said for checking things like $_GET and $_POST you would ideally want to use:
if ( isset($_GET['example']) && $_GET['example'] =='somevalue' ) {
// process data
}
So you always want to firstly make sure that the variable has been set (and not set to null) or in other words exists. Then proceed to check if the variable contains the data that you were expecting. If you try to make reference to a variable which doesn't exist (by not checking isset()) php will give you a notice saying 'undefined variable...etc etc'.
If you wanted to find out if a variable is set but are not concerned too much by what then you could use:
if ( !empty($_GET['example']) ) {
// process data
}
But I would be careful about using empty() on strings in this regard as empty can behave strangely with string data like '0' or ' '.
So I would always do the first one, to a) make sure the variable exists and b) is what you were expecting it to be.
This is something that you'll probably do a lot of and it helps to put together a class/functions which handles this checking for you so you dont have to do it everytime.
function checkValue($key, $value) {
if(array_key_exists($key, $_REQUEST)){
if ($_REQUEST[$key] == $value) {
return true;
} else {
return false;
}
} else {
return false;
}
}
I just use Request as a default instead of switching out (though it is preferable to switch in some cases between POST and GET for security (imo)).
Now you can just call this function anywhere
if (checkValue('Item', 'Tom') === true){} etc
the best is
if((isset($_GET[example]))&&('somevalue'==$_GET['example'])){ ... }
The difference between
'somevalue'==$_GET['example']
AND
$_GET['example']=='somevalue'
If you mistype the == and type = instead, the first notaion will raise an error to notify you.
if((isset($_GET[example]))&&($_GET['example']=='somevalue')){ ... }
When passing a non-existent value by reference, PHP creates the value and sets it to NULL. I noticed it when memory increases were occurring while checking empty values in some functions. Take the following function:
function v(&$v,$d=NULL){return isset($v)?$v:$d;}
$bar = v($foo, $default);
This would be shorthand for:
if(isset($foo))
{
$bar = $foo;
}
else
{
$bar = $default;
}
However, when passing non-existent variables PHP creates them. In the case of variables - they are removed as soon as the method/function ends - but for checking super global arrays like $_GET or $_POST the array element is never removed causing extra memory usage.
$request_with = v($_SERVER['HTTP_X_REQUESTED_WITH']);
Can anyone explain why this happens and if it is a PHP todo fix or a feature for some other crazy use of values?
XeonCross' function v is a shorthand for the often used:
$val= isset($arr['elm']) ? $arr['elm'] : 'default'
to avoid the dreaded 'Undefined index: elm' notice. A nice helper function would be:
function ifset(&$v1, $v2 = null) {
return isset($v1) ? $v1 : $v2;
}
as Xeoncross suggested, so you could write the much nicer
$val = ifset($arr['elm'],'default')
however, this has a lot of interesting (?) quirks in our beloved "language" that we call PHP:
inside the function ifset, $v1 seems UNSET, so it correctly returns the value $v2 and you might conclude that ifset works ok. But afterwards $arr['elm'] is silently set to NULL. So consider the following:
function wtf(&$v) {
if (isset($v))
echo "It is set";
else
echo "It is NOT set";
}
$p=[];
wtf($p['notexist']); => It is NOT set
$p; => [ 'notexist' => NULL ]
But this is another delusion, as the isset() function returns false for NULL values as well:
$x=NULL;
isset($x) => false... huh??
Did we expect this? well.. it is in the documentation, so this is by design as well. Welcome to the wonderful world of php.
The reason you have the memory leak, is because you're telling it to.
When you ask for a reference parameter, PHP will provide you with one. When you are calling a function with an unset variable, PHP will set the variable and then pass the reference to that new variable. When you call it with a superglobal, it creates the missing index. That's because you told it to.
However, I must ask why specifically do you need variable references? 99.9% of the time you don't really need them. I suspect that it'll work just fine to do:
function v($v, $d = null) { return isset($v) ? $v : $d; }
Or, if you really must use references (which you can't get around your original problem with), you should also return a reference:
function &v(&$v, $d = null) {
if (isset($v)) {
return $v;
}
return $d;
}
Otherwise it's pointless to take a reference and not return one...
I am getting tried of if isset($_GET['whatever'])... before the rest of my if statement. E_NOTICE errors are way to handy to turn off and for $_POST variables I have a solution in my init script..
$POST = (is_array( $_POST ) && count( $_POST ) > 0);
I find this helps self posting scripts look clean.
if ($POST) {
// now do something with $_POST...
}
I'm not sure how to dynamically do this if you have no idea what the key is? Can anyone help find a similar solution for $_GET variables?
EDIT:
I simply want if ($_GET['whatever'] == "whatever"); to return false if it's not set and no E_NOTICE errors.
EDIT:
Sorry if I'm unclear I'm looking for a solution for $_GET not $_POST--I only am using $_POST as an example of what I hope to achieve.
Sometimes I use a global GET function:
function GET($key, $default = null) {
return isset($_GET[$key]) ? $_GET[$key] : $default;
}
The main idea of all that mess is simple: every variable in your program should be initialized before use.
Thus, the best you can do is to set all variables centralized, say, at the very top of your script.
But there are some different cases. For the case you posted, you need none of these but
if ($_SERVER['REQUEST_METHOD'] == "POST")
Already answered, but since it wasn't mentioned, also try:
$var = filter_input(INPUT_GET, 'varname');
That will return null if it doesn't exist, without the annoying array notices, and also filters out potential bad stuff in various ways. See also: http://www.php.net/filter
You can make a function to do this for you.
function getVar($item){
return isset($_GET[$item]) ? $_GET[$item] : '';
}
Then you can do if(getVar('whatever') == "whatever").
Here are two methods.
/*
* Makes any request keys into variables of the same name
*/
foreach($_GET AS $key => $value) {
${$key} = ($value);
}
//Assuming a input key of $_GET['whatever']
echo $whatever;
/*
* Casting to an object
*/
$get = (object) $_GET;
//Assuming a input key of $_GET['whatever']
echo $get->whatever
A third option that I can think of is making the $_GET into its own class. PHP overloading is handy trick for doing this.
http://php.net/manual/en/language.oop5.overloading.php
I didn't feel like writing up an example demonstrating this. :)
simple I think you want to check if get value is set then need to do the next step otherwise do different
I like the first answer but need to check thats if it works for you
if(isset($_GET['whatever']){
if ($_GET['whatever'] == "whatever");{
//do the rest
}
else{
//do the rest
}
}
hope it may help if what I think is your need
short
no notice
$key = &$_POST['key'];
This way (inside function) it is depracted, and shows error:
function f($s){}
f(&$_POST['key']);
Fatal error: Call-time pass-by-reference has been removed
When writing these sorts of scripts, I usually do something like this at the top:
$submitted = isset($_POST['submit']) ? true : false;
$username = isset($_POST['username']) ? $_POST['username'] : null;
$password = isset($_POST['password']) ? $_POST['password'] : null;
(etc.)
Then, when testing the values, it looks something like this:
if ($submitted)
{
if ($username && $password)
{
// do stuff with username and password including testing their values
}
}
It seems to work pretty well for me.