How To Check 5 Empty Variables in PHP [closed] - php

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I need to make a conditional statement where the 5 variables should be empty before perform an action. The problem is some variables can be zero, false or NULL value. How to catch all of them?
Which one is better?
If (!$a && !$b && !$c && !$d && !$e) {
// do some action
} else {
exit;
}
OR
If (empty($a) && empty($b) && empty($c) && empty($d) && empty($e)) {
// do some action
} else {
exit;
}
Thank you.

First of all, use "code sample" to show code.
When you use !$a you are actually casting $a to boolean.
The problem here is
$a = 0;
if (!$a) {
echo 'NOT EMPTY';
} else {
echo 'EMPTY';
}
//OUTPUT EMPTY BECAUSE 0 to boolean is FALSE
Same example with NULL value.
About empty i advice you to check the documentation
Read it and choose the way that fit your needs.
Hope this helps

This could be an approach to check multiple variables are empty at once.
<?php
$a = $b = $c = $d = $e = '';
#$b = 5; // comment out to go on else block
if (empty($a . $b . $c . $d . $e)){
echo "All variables are empty, do what you want to do man";
}else{
echo "One of variable is not empty";
}
?>

Related

Replacing Numbers with text in php [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 10 months ago.
Improve this question
So my taslk is to program two numbers randomly (for example 0 and 1) and then replace the numbers with "Hello" and "bye". I've done the generating it rendomly part, but now I'm struggling with the replacing Part. It would be cool If the solution would be by using "if" and "else"
Here's what i've done so far,
thank you in advance
<?php
$zaehler = 0;
while($zaehler < 10)
{
echo mt_rand(0, 1);
if(0)
{
echo "bye" ;
}
else (1) ;
{
echo "hello" ;
}
$zaehler++;
}
?>
For your case, just use a comparison statement
e.g.
if($result==0) { // do something;} else {// do another thing; }
(the $result will only be either 0 or 1, so just use one if-then-else)
<?php
$zaehler = 0;
while($zaehler < 10){
$result=mt_rand(0, 1);
echo $result;
if($result==0) {
echo "bye" ;
} else {
echo "hello" ;
}
$zaehler++;
}
?>
So i just saw your post,
First, you need to assign mt_rand to a variable.
Afer your statement IF isnt correct, you need to evaluate something like this $i === 0
And about your else you need an else if, so you can take a look to this code ;)
$idx = 0;
while ($idx < 10) {
$random_int = mt_rand(0, 1);
if ($random_int === 0) {
echo "bye\r\n";
} else if ($random_int === 1) {
echo "hello\r\n";
}
$idx++;
}

where to write else condition inside loop within another loop? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
If the phone number matches , I am able to print "Yes". If it doesnot match , i need to print "No". But if i include else part , its executing only else part. Please guide me how and where to write else part.
<?php if($re['phone_v'] == "1"){
echo "Yes";
}else if($re['phone_v'] == "0"){
for($i=0;$i < count($crusers);$i++) {
if ($re['phone'] == $crusers[$i]['phone']) {
echo "Yes";
}
}
}
?>
I am checking condition inside table in view. small thing is making complicated.
This will help you.
$re['phone_v'] = 0;
$re['phone'] = 1;
$crusers[0]['phone'] = 1;
if($re['phone_v'] == "1"){
echo "Yes";
}else{
if($re['phone_v'] == "0")
{
for($i=0;$i < count($crusers);$i++)
{
if ($re['phone'] == $crusers[$i]['phone'])
{
echo "Yes11";
}else{
echo "No";
}
}
}
}

nested if-else statement with same else code [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I have the following code and want to know if there is a better way to use the if-else with same result other than using the same else three times?
if($condition1) {
// some code to get condition 2
if($condition2) {
// some code to get condition 3
if($condition3) {
$dt = $something;
} else {
$dt = "";
}
} else {
$dt = "";
}
} else {
$dt = "";
}
You could easily get rid of some of the extra else statements.
$dt = ""; // Assign $dt in the beginning
if ($condition1) {
// some code to get condition 2
if ($condition2 && $condition3) {
// some code to get condition 3
$dt = $something;
}
}
Two ways to avoid nested statements.
using a function
$dt = doSomething($params);
function someFunction ($params) {
if (!$condition1) {
return "";
}
// do stuff for condition 1
if (!$condition2) {
return "";
}
// do stuff for condition 2
if (!$condition3) {
return "";
}
return $something;
}
using a do/while statement
do {
$dt = "";
if (!$condition1) {
break;
}
// do stuff for condition 1
if (!$condition2) {
break;
}
// do stuff for condition 2
if (!$condition3) {
break;
}
$dt = $something;
} while (0); // since this will evaluate to false it will not loop at all.

Losing array during variable assignment as part of a condition [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I'm attempting to troubleshoot some code and something is happening that I can't make any sense of... I have a $forum object which contains a threadExists method, which returns an associative array of any results found or false otherwise.
The following will print the array as expected:
if (!$test = $forum->threadExists($thread_id)) {
// do something
}
echo '<pre>';
var_dump($test);
echo '</pre>';
exit;
However; by adding a condition the screen will simply print bool(true):
if (!$test = $forum->threadExists($thread_id) || $test['topic_id'] != $topic_id) {
// do something
}
echo '<pre>';
var_dump($test);
echo '</pre>';
exit;
Why is the array lost?
I'm using PHP 5.4.12.
operator precedence causes it to be interpreted like this
if (!($test = ($forum->threadExists($thread_id) || $test['topic_id'] != $topic_id))) {
// do something
}
more clearly,
$test = $forum->threadExists($thread_id) || $test['topic_id'] != $topic_id;
if (!$test) {
// do something
}
you can force the correct behavior with parenthesis
if (!($test = $forum->threadExists($thread_id)) || $test['topic_id'] != $topic_id) {
// do something
}
personally, I would write it like the following, because I hate code that is even slightly tricky to read
$test = $forum->threadExists($thread_id);
if (!$test || $test['topic_id'] != $topic_id) {
// do something
}
Read it like this:
if(!$test = $forum->threadExists($thread_id) || $test['topic_id'] != $topic_id)
Assign $forum->threadExists($thread_id) || $test['topic_id'] != $topic_id to $test
Negate and check the value of $test
And since $forum->threadExists($thread_id) || $test['topic_id'] != $topic_id evaluates to true, so you get true assigned to $test.
Fix is:
if((!$test = $forum->threadExists($thread_id))||($test['topic_id'] != $topic_id))
Parenthesis issue. You're assigning to $test the value of the compound condition, so it will have a boolean value based on whether either side of it resolves to true. Try:
if (!($test = $forum->threadExists($thread_id)) || $test['topic_id'] != $topic_id) {

How many variable checks should you do? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Something I've never been sure about is how many variable checks to do in PHP. For example take the following piece of code. I am not checking any of the variables before I assign them or pass them to a function to see if they contain what I expect
$carId = '12';
$aCar = fetchCar($carId);
$make = $aCar['make'];
$model = $aCar['model'];
$yearMade = $aCar['year'];
$age = calcAge($yearMade);
Now if I add some checks
$carId = '12';
if(is_numeric($carId))
{
$aCar = fetchCar($carId);
if(isset($aCar['make']) && is_string($aCar['make']))
{
$make = $aCar['make'];
}
else
{
//Report error
}
if(isset($aCar['model']) && is_string($aCar['model']))
{
$model = $aCar['model'];
}
else
{
//Report error
}
if(isset($aCar['year']) && is_numeric($aCar['year']))
{
$yearMade = $aCar['year'];
$age = calcAge($yearMade);
}
else
{
//Report error
}
}
else
{
//Report errors
}
The code is now better but is it a bit too excessive and bloated? Should I be doing this many checks?
If I shouldn't be doing this many checks where do you draw the line between what you should and shouldn't check?
This is the dilemma of a dynamic type language.
It depends heavily on what fetchCar() function is doing.
The approach i would take is assume fetchCar is returning a car array or throwing exception.
If you combine this with good exception handling logic you can end up with clean and stable code.
For example:
function fetchCar($id) {
$car = queryDatabaseSomehow();
if (empty($car)) {
throw new ExceptionNotFound();
}
//eventually you can put your type checking here?
if (!isset($car['x']) || !is_string($car['x'])) {
throw new ExceptionDb();
}
}
echo fetchCar(3)['make'];
Also if you would like to do this super-proper and go fully OOP, Car should become a class with make,model and year as its members. fetchCar() would return Car or throw Exception. But this is not always desirable of course.
One issue that some people haven't noticed. Be wary of using is_string:
<?php
$var = "test";
$var['something'] = 2;
if(is_string($var['something'])) {
echo "Hello world!"; // Will echo this because $var is a string!
} else {
echo "Hello hell!";
}
echo "<br/>";
echo $var['something']; // returns 2
?>
PHPFiddle.
Compare it with this:
$var = array('something' => 2);
if(is_string($var['something'])) {
echo "Hello world!"; // $var is now an array
} else if (is_numeric($var['something'])) {
echo "Hello hell!"; // Will echo this because $var is string!
}
echo "<br/>";
echo $var['something'];
You need to check whether $var is an array, as it might give you unexpected results. isset($var['something']) will return true in the first example.
To answer your question, I don't think those are too many checks. It really depends on what fetchCar() does and how it gets the data. If you can't trust it (say, it's based on user data) then you should perform all these checks. If not, then there is no point really.
I rather turn it all into a function that can be reused for these cases.
function check_keys($arr_check, $arr_cond) {
$boo_success = TRUE;
foreach(array_keys($arr_cond) as $h)
if (in_array($arr_cond[$h], array('is_string', 'is_numeric'))) {
if ( ! isset($arr_check[$h]) or ! ($arr_cond[$h]($arr_check[$h]))) {
$boo_success = FALSE;
echo "The key {$h} is missing!";
// If run through a class, $this->errors[] = 'error message';
}
} else {
$boo_success = FALSE;
echo 'Invalid function';
}
return $boo_success;
}
$arr_keys = array('make' => 'is_string',
'model' => 'is_string',
'year' => 'is_numeric');
if (check_keys($aCar, $arr_keys)) {
// Run successful stuff
}

Categories