Empty variable define in php - php

Before doing something with $error:
$error = NULL;
In some script's saw:
$error = '';
$error = false;
$error = 0;
Which method is 'better' or maybe it depends in which situation i use
it ?
What's your suggestion ?

Depends on your design:
Are you setting it as an Object in case of error? Use NULL.
Are you setting it to true in case of error? Use false.
Are you setting it as a number of some sort in case of error? Use 0.
Are you setting it to a string to describe the error? Use ''.
A better way to indicate errors would be throwing Exceptions though, rather than setting a variable and determine the error according to it.

There is no canonical answer to this question. As long as you use one of these semaphores consistently, you can use anything you want. Because PHP is loosely-typed, all of these values are "falsy" and can be evaluated in a boolean comparison as FALSE.
That said, there is more of a difference between the empty string and the others, so I'd stick with NULLs and FALSEs in this sort of scenario.

1.
$v = NULL;
settype($v, 'string');
settype($v, 'int');
settype($v, 'float');
settype($v, 'bool');
settype($v, 'array');
var_dump($v);
2.
$v = NULL;
var_dump( (string) $v);
var_dump( (int) $v);
var_dump( (float) $v);
var_dump( (bool) $v);
var_dump( (array) $v);

It depends upon the conditions where you need to use the $error. Using a NULL is what I chose mostly as I deal more with MySQL clauses and all!

Related

Message: Trying to get property of non-object error in php [duplicate]

Is there in PHP something similar to JavaScript's:
alert(test || 'Hello');
So, when test is undefined or null we'll see Hello, otherwise - we'll see the value of test.
I tried similar syntax in PHP but it doesn't seem to be working right... Also I've got no idea how to google this problem..
thanks
Edit
I should probably add that I wanted to use it inside an array:
$arr = array($one || 'one?', $two || 'two?'); //This is wrong
But indeed, I can use the inline '? :' if statement here as well, thanks.
$arr = array(is_null($one) ? "one?" : $one, is_null($two) ? "two ?" : $two); //OK
you can do echo $test ?: 'hello';
This will echo $test if it is true and 'hello' otherwise.
Note it will throw a notice or strict error if $test is not set but...
This shouldn't be a problem since most servers are set to ignore these errors. Most frameworks have code that triggers these errors.
Edit: This is a classic Ternary Operator, but with the middle part left out. Available since PHP 5.3.
echo $test ? $test : 'hello'; // this is the same
echo $test ?: 'hello'; // as this one
This only checks for the truthiness of the first variable and not if it is undefined, in which case it triggers the E_NOTICE error. For the latter, check the PHP7 answer below (soon hopefully above).
From PHP 7 onwards you can use something called a coalesce operator which does exactly what you want without the E_NOTICE that ?: triggers.
To use it you use ?? which will check if the value on the left is set and not null.
$arr = array($one ?? 'one?', $two ?? 'two?');
See #Yamiko's answer below for a PHP7 solution https://stackoverflow.com/a/29217577/140413
echo (!$test) ? 'hello' : $test;
Or you can be a little more robust and do this
echo isset($test) ? $test : 'hello';
As per the latest version use this for the shorthand
$var = $value ?? "secondvalue";
One-liner. Super readable, works for regular variables, arrays and objects.
// standard variable string
$result = #$var_str ?: "default";
// missing array element
$result = #$var_arr["missing"] ?: "default";
// missing object member
$result = #$var_obj->missing ?: "default";
See it in action: Php Sandbox Demo
I'm very surprised this isn't suggested in the other answers:
echo isset($test) ? $test : 'hello';
From the docs isset($var) will return false if $var doesn't exist or is set to null.
The null coalesce operator from PHP 7 onwards, described by #Yamiko, is a syntax shortcut for the above.
In this case:
echo $test ?? 'hello';
If you want to create an array this way, array_map provides a more concise way to do this (depending on the number of elements in the array):
function defined_map($value, $default) {
return (!isset($value) || is_null($value)) ? $default : $value;
// or return $value ? $default : $value;
}
$values = array($one, $two);
$defaults = array('one', 'two');
$values = array_map('defined_map', $values, $defaults);
Just make sure you know which elements evaluate to false so you can apply the right test.
Since php7.4, you can use the null coalescing assignment, so that you can do
$arr = array($one ??= "one?", $two ??= "two ?");
See the docs here
There may be a better way, but this is the first thing that came to my mind:
echo (!$test) ? "Hello" : $test;
Null is false in PHP, therefore you can use ternary:
alert($test ? $test : 'Hello');
Edit:
This also holds for an empty string, since ternary uses the '===' equality rather than '=='
And empty or null string is false whether using the '===' or '==' operator. I really should test my answers first.
Well, expanding that notation you supplied means you come up with:
if (test) {
alert(test);
} else {
alert('Hello');
}
So it's just a simple if...else construct. In PHP, you can shorten simple if...else constructs as something called a 'ternary expression':
alert($test ? $test : 'Hello');
Obviously there is no equivalent to the JS alert function in PHP, but the construct is the same.
alert((test == null || test == undefined)?'hello':test);
I recently had the very same problem.This is how i solved it:
<?php if (empty($row['test'])) {
echo "Not Provided";}
else {
echo $row['test'];}?></h5></span></span>
</div>
Your value in the database is in variable $test..so if $test row is empty then echo Not Provided

why does in_array return true when a value only begins with what is in an array

I've noticed a strange thing about PHP's in_array function. For some reason, it will only check if the first character(s) of the needle match with any of the values of the haystack - as opposed to if the whole needle is in the haystack.
For example, in a situation where $string equals 1thisisatest, the following script will return In array.
$allowed = [0, 1];
if(in_array($string, $allowed)){
echo "In array";
} else {
echo "Not in array";
}
Whereas if $string equals 2thisatest, the script will return Not in array.
Now either this is a bug, or a very strange feature. Wouldn't you want it to check needles against the haystack exactly as they appear?
If this is, indeed, how the function is supposed to work, how does one go about getting the intended result without iterating over every single element in the array? Seems kind of pointless.
EDIT:
Some of you are saying to use strict mode. This is all fine and dandy, until you checking against $_GET data, which is always a string. So the following will return false:
$value = $_GET["value"]; // this returns "1"
in_array($value, [0, 1], true)
Because the in_array function uses the == operator. Thus 1 == "1thisisatest" - so, in_array will return true.
To fix this you can enabled strict mode:
// in the third parameter (to use === instead of ==)
in_array($search_value, $array_name, true)`
in_array by default uses == which will follow the rules of type juggling
The solution is to use strict comparison:
in_array($value, [0, 1], true);
If you are concerned about $_GET variables you need to ensure you always validate and sanitize your input before using it otherwise you might end up with strange results:
$value = filter_input(INPUT_GET, 'value', FILTER_VALIDATE_INT);
in_array($value, [0, 1], true);
It is always good to validate and sanitize your input to avoid things like e.g. someone calling your URL as ?value[]=1 which will mean $_GET['value'] will be an array causing (most likely) errors in the best case and strange undocumented behaviour in the worst case.
Make $allowed an array of strings and use strict mode.
$allowed = ["0", "1"];
if (in_array($_GET['value'], $allowed, true)) {
echo "In array";
} else {
echo "Not in array";
}
If you need to be more accurate you have to put the boolean true in your function like this:
$string = "1thisisatest";
$allowed = array(0, 1);
if(in_array($string, $allowed, true)){
echo "In array";
} else {
echo "Not in array";
}

set value when not empty via ternary expression

I have a really quick question for you:
I read data from an Excel sheet and want to transform it into an assoc array. But sometimes there are no values given in some cells. So if this occurs I want to set the value of the array to 0.
right now I do it like that with the ternary operator and I'm glad I discovered that today:
(isset($excel->sheet[0]['cells'][$row][$value]) ? $excel->sheet[0]['cells'][$row][$value] : 0)
Is there a whay to shorten the repitition in this case? It works but it ain't that pretty :(
Although this is not recommended, I would go the following way (PHP 5.3):
(#$excel->sheet[0]['cells'][$row][$value] ? : 0);
Error suppression operator is a mess, but in this case the only thing you suppress is a well-known notice about undefined variable.
Another option (as stated by Álvaro G. Vicario) could be a simple cast to int (as NULL casts to 0):
(int)#$excel->sheet[0]['cells'][$row][$value];
Another option is making a function to check the existence of such variable – maybe it's a little over-engineering, overkill or just too much –:
function iset($array, $output) {
$args = func_get_args();
$val = $array;
for ($i = 1; $i < count($args) - 1; $i++) {
if (!isset($val[func_get_arg($i)])) {
return func_get_arg(func_num_args() - 1);
}
$val = $val[func_get_arg($i)];
}
return $val;
}
Then use the function like this:
$var = iset($excel->sheet, 0, 'cells', $row, $value, "DEFAULT_VALUE");

Finding common characters in strings

I am tring this method to find the common characters in two strings namely, $a and $r, but the first character isn't getting printed . Moreover the $already collects the common characters and prevents them from being printed for multiple times( I need each character to be printed once only) but it isn't doing so. Please tell me what errors I am making.
<?php
$a="BNJUBCI CBDIDIBO";
$r="SBKJOJLBOU";
$already="";
for($i=0;$i<strlen($r);$i++)
{
if (stripos($a,$r[$i])!=FALSE)
{
if (stripos($already,$r[$i])==FALSE)
{
$already=$already.$r[$i];
echo "already=".$already."<br>";
echo $r[$i]."<br>";
}
}
}
?>
Use !==FALSE instead of !=FALSE. The problem is that stripos returns 0 if the needle is at the start of the haystack, and 0 is falsy. By using !== you are forcing it to ensure the result is actually false, and not just 0.
This is actually listed in the docs. An "RTM" might be appropriate here.
Warning
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
The simplest way to find the intersection of the two strings in PHP is to turn them into arrays and use the built-in functions for that purpose.
The following will show all the unique and common characters between the two strings.
<?php
$a="BNJUBCI CBDIDIBO";
$r="SBKJOJLBOU";
$a_arr = str_split($a);
$r_arr = str_split($r);
$common = implode(array_unique(array_intersect($a_arr, $r_arr)));
echo "'$common'";
?>
I would think a much simpler solution to this would be to make the strings into arrays and compare those no?
Something like:
<?php
$a="BNJUBCI CBDIDIBO";
$r="SBKJOJLBOU";
$shared = implode( '' , array_intersect( str_split($a) , str_split($r) ) );
?>
That should return you a string of all the characters in $a that are present in $r

Can boolean needle be passed to in_array?

Can I pass false as a needle to in_array()?
if(in_array(false,$haystack_array)){
return '!';
}else{
return 'C';
}
The $haystack_array will contain only boolean values. The haystack represents the results of multiple write queries. I'm trying to find out if any of them returned false, and therefore not completed.
PHP won't care what you pass in as your 'needle', but you should probably also use the third (optional) parameter for in_array to make it a 'strict' comparison. 'false' in PHP will test as equal to 0, '', "", null, etc...
Yep, just like in your example code. Because in_array returns a boolean to indicate whether the search was successful (rather than returning the match), it won't cause any problems.
There's got to be a better way.
<?php
echo (in_array(false,array(true,true,true,false)) ? '!' : 'C');
echo (in_array(false,array(true,true,true,true)) ? '!' : 'C');
Output:
!C
Yes you can but why don't you do it with a single boolean variable like this:
$anyFalseResults = false;
... your query loop {
// do the query
if( $queryResult == false ) $anyFalseResults = true;
}
at the end of the loop $anyFalseResults will contain what you are looking for.

Categories