I have a function that checks if a variable is exists.
function variable( &$var, $default = NULL )
{
if( (!isset($var) && !is_array($var)) || empty($var) )
{
return FALSE;
}
elseif( is_array($var) && count($var) <= 0 )
{
return FALSE;
}
else
{
return $var;
}
}
My problem is, that this function creates an array when I pass an array element reference like $array['element'] the array $array and the index 'element' is created even if it did not exists before.
What the function is supposed to do is having something like echo variable($var); which does no produce an error even if $var is not defined.
Is there a way to delete this again or even better not let the function create the array?
Thanks.
See here: http://ch.php.net/manual/de/function.array-key-exists.php
array_key_exists is the "key", no pun intended :-)
like so:
if (array_key_exists('element', $array)({
// do the fan dango
}
To delete, you can use unset($array['element']); or unset($array); depending on your goal.
For making sure the array turns into a string, just use implode("",$array);
Related
Is there any way of checking if a variable is not null and then to check if variable has nested associative array keys using a shorthand? Something like optional chaining for associative arrays?
Example of what I would like to make concise:
public $arr;
//$arr gets set as an associative array somewhere else in the code.
function someFunc() {
if ($this->arr && $this->arr['key1'] && $this->arr['key1']['key2'] == 'Some Value') { // shorten this line?
// Do Something Cool!
}
}
I am looking for something similar to Optional Chaining in Javascript e.g. :
if (obj.key1?.key2 == 'Some Value') {
// Do something kool
}
There is a high probability that this is a duplicate and I apologize in advance if that is the case. I tried searching for this for associative arrays and could not find anything specific.
You could keep the if statement intact, but replace $this->arr && $this->arr['key1'] with an Null Coalescing Operator (??), so if those aren't defined, it will use the fallback, that isn't equal to the test string:
if (($this->arr['key1']['key2'] ?? false) == 'Some Value') {
// Do Something Cool!
}
So if $this->arr['key1']['key2'] is defined, you'll compare that to Some Value, otherwise, if it's not defined, you'll compare (eg) false to Some Value witch will remain false.
Use the php function isset: https://www.php.net/manual/en/function.isset.php
It will check for multiple keys: if( isset($this->arr['key1']['key2'] ) {...} and also includes a null check.
If you for some reason need to shorten it even more, simply decompose it to another function:
public $arr;
//$arr gets set as an associative array somewhere else in the code.
function someFunc()
{
if ($this->checkForSomeValue($this->arr, 'Some Value', 'key1', 'key2')) { // shorten this line?
// Do Something Cool!
}
}
function checkForSomeValue(array $arr, string $valueToCheck, ...$keys)
{
$valueCompare = $arr;
foreach($keys as $key)
{
if(!isset($valueCompare[$key]))
{
$valueCompare = null;
break;
}
else
{
$valueCompare = $valueCompare[$key];
}
}
return $valueCompare && $valueCompare === $valueToCheck;
}
I've updated the answer to allow supplying keys
I always find myself writing something like:
if(isset($var))
{
DoSomethingWith($var);
}
else
{
DoSomethingWith(null);
}
or
if(isset($arr["key"]))
{
DoSomethingWith($arr["key"];
}
else
{
DoSomethingWith(null);
}
My question is exacly this:
Is there a way to write a get_var_if_set() function so that you can simply write...
DoSomethingWith(get_var_if_set($var));
/// and
DoSomethingWith(get_var_if_set($arr["key"]));
....WITHOUT notifying if $var doesn't exists or that $arr doesn't have a set value for "key"?
I guess it should be something like this:
function get_var_if_set($a)
{
return (isset($a) ? $a : null);
}
But that doesn't work because calling get_var_if_set() with unset variables will always generate a Notice, so it might need a little magic.
Thanks all folks.
Edit
A user who deleted his answer suggested to pass variables by reference, as PHP will pass null if the $variable doesn't exist.
So that would be perfect, take a look at these solutions (which might probably be equivalent):
function get_var_if_set(&$a) { return (isset($a) ? $a : null); }
function get_var_if_set(&$a) { return $a ?? null; } // Only in PHP 7.0+ (Coalescing operator)
Note: Coalescing operator suggested by Koray Küpe
The problem as you can see is that they initialize the passed variables somehow in the return statement.
We don't want that.
If you use PHP 7.0+ you can use null coalescing operator.
return $a ?? null;
Note: The operator checkes whether the variable exist and not empty. So, if the variable is already set but empty, it will return the null variable already.
The problem is not the var itself, but the key of the array key in this:
DoSomethingWith(get_var_if_set($arr["key"]))
So the only solution is to check for the array and the key you're looking for.
function get_var_if_set($a, $key = null)
{
if(is_array($a) && array_key_exists($key, $array)) {
return $a[$key];
} else {
return (isset($a) ? $a : null);
}
}
In the past when I needed to check if a variable was set and also a number, I would do:
if( isset($_GET['var']) && is_numeric($_GET['var']) )
But I think that's kind of ugly, especially when I need to check a bunch of variables in the same if statement, so I made a function:
function setAndNum($var)
{
if(isset($var) && is_numeric($var))
return 1;
else
return 0;
}
The problem is that when I pass an undefined variable to the function, like this (supposing the variable in the GET array is undefined):
if( setAndNum($_GET['var']) )
I get the php error:
Notice: Undefined index: ...
So the whole purpose of the function is basically defeated (or half the purpose, at least ;) ).
One thing that confuses me is how the isset() function works, and why I can pass an undefined variable to it but not to my own function?
Is it possible to make my setAndNum() function work?
Your problem is with $_GET being an array. When you pass $_GET['var'] to your function, this array value is already looked up and used as an argument to the function. Therefore you cannot effectively check the presence of 'var' in $_GET from within this function. You could rewrite it a bit to make it work for array values, something like this:
function setAndNum($key, $array)
{
if(array_key_exists($key, $array) && is_numeric($array[$key]))
return 1;
else
return 0;
}
Then call it like this:
if( setAndNum('var', $_GET) )
It's good practice to verify a key exists before using it:
if (array_key_exists($_GET, 'var')) {
// do stuff with $_GET['var']
}
function setAndNum(&$var)
{
if(isset($var) && is_numeric($var))
return 1;
else
return 0;
}
Please, try using this version:
function setAndNum(&$var)
{
if(isset($var) && is_numeric($var))
return 1;
else
return 0;
}
You can use the # operator to prevent error reporting:
setAndNum(#$_GET['var']);
This way, the error message of the non-existant index will not be printed, and the return value will be 0.
You could also write two functions, one that checks for an array and one that checks for normal variable
function setAndNum($var)
{
if(isset($var) && is_numeric($var))
return 1;
else
return 0;
}
function setAndNumArray($array, $key)
{
if(isset($array) && isset($array[$key]) && is_numeric($array[$key]))
return 1;
else
return 0;
}
if you are using variables from GET or POST method you may do like this as these are super globals.
function setAndNum()
{
if(isset($_GET['var']) && is_numeric($_GET['var']))
return 1;
else
return 0;
}
now coming to your another query. isset checks whether a variable is s et or not like
if(isset($_POST['submit']))
{
// any code under button click
}
I'm coding a worksheet app for a printer company.
I'm getting flood of forms.
For every single input field I have to check if the $_POST variables are set, and if, so echo back the value. (In case of some error, for example after a validation error, the user shouldn't retype the whole form)
Sample code:
if(isset($_POST['time'])&&!empty($_POST['time'])){echo $_POST['time'];}
I had to implement this about a hundred times.
So I tried to figure out some kind of function to make this simple and readable.
Something like this:
function if_post_echo($key, $default = "") {
if(isset($_POST[$key])&&!empty($_POST[$key])){
echo $_POST[$key];
}else{
echo $default;
}
}
But this wont work.
I have tried to pass in the $_POST for the $key variable like this:
if_post_echo($_POST['time'])
function if_request_echo($key, $default = "") {
if(isset($key)&&!empty($key)){
echo $key;
}else{
echo $default;
}
}
And I also tried this:
function if_request_echo($key, $default = null) {
return isset($_REQUEST[$key])&&!empty($_REQUEST[$key]) ? $_REQUEST[$key] : $default;
}
Without any reasonable outcome.
The question:
How can I forge a function that looks for the necessary $_POST variable and returns it or if its unset then returns an empty string.
And is there a way to do this for $_GET and $_REQUEST, too? (Or simply duplicate?)
Your PHP testing function:
<?php
function test_req($key, $default = '') {
if(isset($_REQUEST[$key]) and
!empty($_REQUEST[$key])) {
return $_REQUEST[$key];
} else {
return $default;
}
}
?>
Then in your form HTML:
<input name="my_field" value="<?php echo htmlentities(test_req('my_field')); ?>" />
$_REQUEST (linked) is a PHP super global that contains both POST ($_POST) and GET ($_GET) request parameters.
If you only want to capture POST request parameters then it would be:
<?php
function test_req($key, $default = '') {
if(isset($_POST[$key]) and
!empty($_POST[$key])) {
return $_POST[$key];
} else {
return $default;
}
}
?>
For example.
If you have a large amount of fields, I would propose that you also use an array of defaults:
$defaults = array(
"time" => "default",
"name" => "enter name here",
"text..." => "...",
);
$fields = array_filter($_POST) + $defaults;
$fields will then contain a list of form values with either the POST data or a preset default. No isset, see?
array_filter man page particularly: If no callback is supplied, all entries of input equal to FALSE will be removed. Goes some way to explaining the working behind this solution.
This should work:
function if_post_echo($key, $default = ''){
if(isset($_POST[$key]) AND !empty($_POST[$key]){
echo $_POST[$key];
}
echo $default;
}
If you're having problems I recommend that you try var_dump($_POST) or print_r($_POST) to see if everything has been properly posted.
Just to note, this is redundant:
isset($_POST[$key]) && !empty($_POST[$key])
An unset variable is going to always be "empty", so isset() is implied in your empty() call.
For your logic you can achieve the same result with just:
!empty($_POST[$key])
Your first function works perfectly to me.
Why do you think it doesn't work?
However, a better variant would be
function _post($key, $default = "") {
if(isset($_POST[$key])){
return $_POST[$key];
}else{
return $default;
}
}
To use it :
echo $_post($key); // You could define the message as a second parameter.
function requireArray( $array, $required ) {
foreach( $required as $k=>$v ) {
if ( !isset($array[$k]) || empty($array[$k]) )
return false;
}
return true;
}
#call like this:
requireArray($_POST, array('time', 'username', 'foo'));
If you want to know specifically:
function missingFrom( $array, $required ) {
$r = array();
foreach( $required as $k ) {
if ( !isset($array[$k]) || empty($array[$k]) )
$r[] = $k;
}
return $r;
}
Called like previous function.
Your method seems to work fine here:
function if_post_echo($key, $default = "") {
if(isset($_POST[$key])&&!empty($_POST[$key])){
echo $_POST[$key];
}else{
echo $default;
}
}
I made a simple input with the name test and the form method is POST and using echo if_post_echo('test');.
It posted on the page what was in the text box.
This feature is being added in PHP 7 as the "Null Coalesce Operator" using two question marks:
echo ($_GET['message'] ?? 'default-if-not-set');
https://wiki.php.net/rfc/isset_ternary
I want to check if a variable called $smth is blank (I mean empty space), and I also want to check if it is set using the function I defined below:
function is_blank($var){
$var = trim($var);
if( $var == '' ){
return true;
} else {
return false;
}
}
The problem is I can't find a way to check if variable $smth is set inside is_blank() function. The following code solves my problem but uses two functions:
if( !isset($smth) || is_blank($smth) ){
// code;
}
If I use an undeclared variable as an argument for a function it says:
if( is_blank($smth) ){
//code;
}
Undefined variable: smth in D:\Www\www\project\code.php on line 41
Do you have a solution for this?
Solution
This is what I came up with:
function is_blank(&$var){
if( !isset($var) ){
return true;
} else {
if( is_string($var) && trim($var) == '' ){
return true;
} else {
return false;
}
}
}
and works like a charm. Thank you very much for the idea, NikiC.
Simply pass by reference and then do isset check:
function is_blank(&$var){
return !isset($var) || trim($var) == '';
}
Whenever you use a variable outside of empty and isset it will be checked if it was set before. So your solution with isset is correct and you cant' defer the check into the is_blank function. If you only want to check if the variable is empty, use just the empty function instead. But if you want to specifically check for an empty string after a trim operation, use isset + your is_blank function.
Use empty. It checks whether the variable is either 0, empty, or not set at all.
if(empty($smth))
{
//code;
}