Detect which condition is false in multiple if statement - php

I try to shorten my code, and so I come along to shorten the following type of if statement:
// a,b,c,d needed to run
if ( empty(a) ) {
echo 'a is empty';
} elseif ( empty(b) ) {
echo 'b is empty';
} elseif ( empty(c) ) {
echo 'c is empty';
} elseif ( empty(d) ) {
echo 'd is empty';
} else {
// run code with a,b,c,d
}
Is there a way to detect which one of the conditions was false (is emtpy)?
if ( empty(a) || empty(b) || empty (c) || empty(d) ) {
echo *statement n*.' is empty';
} else {
// run code with a,b,c,d
}
I thought about a for loop, but that would need massive code changes.
Maybe someone can point me to the right direction.
Thanks in advance :)
Jens

You can go with setting a variable for each condition and output this
if ( (($t = 'a') && empty($a)) || (($t = 'b') && empty($b)) || (($t = 'c') && empty($c)) || (($t = 'd') && empty($d)) ) {
echo "{$t} is empty";
} else {
// run code with a,b,c,d
}
The assignment ($t='a|b|c|d' ) will always be true and it the testet var is empty your condition will fail because of true && false in the condition
But in terms of readibility i would rather go with any of the other answers.

Using compact, array_filter and array_diff:
$arr = compact( 'a', 'b', 'c', 'd' );
if( count( $empty = array_diff( $arr, array_filter( $arr ) ) ) )
{
echo key( $empty ) . ' is empty';
}
else
{
echo 'OK';
}
By this way, in $empty you have all empty values. So you can echo a warning for all keys:
echo 'Empty: ' . implode( ', ', array_keys( $empty ) );

For this kind of condition I would recommend you to use switch, which is more optimised way of doing it, like this:
$empty = "";
switch ($empty) {
case $a:
echo "a is empty"
break;
case $b:
echo "b is empty"
break;
case $c:
echo "c is empty"
break;
default:
echo "nothing is empty";
}

Personally, I'd probably use a variable variable. But this is just cos I like them, some don't
// the variables somewhere else in your code
$a = 1;
$b = null;
$c = '';
$d = 4;
// do your check
$arr = ['a','b','c','d']; // the names of the variables you want to check
foreach($arr as $var) {
if(empty($$var)) {
echo $var . ' is empty'.PHP_EOL;
}
}
Will output
b is empty
c is empty
example

Use array_search()
<?php
$arr = array('a'=>1,'b'=>2,'c'=>null,'d'=>4); //make an array of variables
echo "Null variable : ".array_search(null, $arr); // check for null item
?>
This will Output :
Null variable : c

Related

how to find multiple comma separated string in main string

I have this main sting.
S,SR,DSR,DS,FX,FXS,SR,DS,S,SR,DS,FX,S,SR,DS,FX,FXS
and i want to find each of the following strings ..
DSR and FXS
i have tried by following code but it can not given me perfect result.
code...
<?php
$mainstring ="S,SR,DSR,DS,FX,FXS,SR,DS,S,SR,DS,FX,S,SR,DS,FX,FXS";
$needed = "DSR,FXS";
if( strpos( $mainstring, $needed ) !== false ) {
echo "Found";
}else{
echo "Not match";
}
?>
One solution would be to explode those strings by comma and verify if the resulted arrays intersection count is the same as your search:
$mainstring ="S,SR,DSR,DS,FX,FXS,SR,DS,S,SR,DS,FX,S,SR,DS,FX,FXS";
$needed = "DSR,FXS";
$mainStringArr = explode(',', $mainstring);
$neededArr = explode(',', $needed);
if (count(array_unique(array_intersect($mainStringArr, $neededArr))) == count($neededArr)) {
echo 'found';
} else {
echo 'not found';
}
Explode the $needed string by command and traverse the array to and compare each value of array into $mainstring using strpos() function. If found then put that value into $arrResut with 'Found' or 'not found' value and finally print the $arrResult to view which value of $needed is found and which is not.
Also, we increment $cntNeeded variable if value if found. at the end of foreach loop compare value of $cntNeeded & $arrNeeded are same then all values are found into $mainstring else not.
$mainstring ="S,SR,DSR,DS,FX,FXS,SR,DS,S,SR,DS,FX,S,SR,DS,FX,FXS";
$needed = "DSR,FXS";
$arrNeeded = explode(",", $needed);
$arrResult = array();
$cntNeeded = 0;
foreach($arrNeeded as $index => $needed) {
if( strpos( $mainstring, $needed ) !== false ) {
$arrResult[$needed] = "Found";
$cntNeeded++;
}
else{
$arrResult[$needed] = "Not match";
}
}
print("<pre> :: arrResult ::");
print_r($arrResult);
print("</pre>");
if($cntNeeded == count($arrNeeded)) {
echo "Found";
}
else {
echo "Not match";
}

How to compare two arrays using a for loop?

I have 2 explode arrays from the database. and this is what i did.
$searches = explode(',', $searchengine);
$icons = explode(',', $icon);
$b = count($searches);
$c = count($icons);
I also made an array to compare each explode array to.
$searchesa = array("google","yahoo","bing");
$d = count($searchesa);
$iconsa = array("facebook","twitter","googleplus","linkedin","pinterest","delicious","stumbleupon","diigo");
$y = count($iconsa);
Then i used for loops to travel to different array indexes. But the result is wrong, and sometimes I have an error which says UNDEFINED OFFSET.
for ($a=0; $a <$d ; $a++) {
if ($searches[$a] == $searchesa[$a])
{echo '<br>'.$searchesa[$a].': check ';
}else
echo '<br>'.$searchesa[$a].': chok ';
}
for ($x=0; $x <$y ; $x++) {
if ($icons[$x] == $iconsa[$x])
echo '<br>'.$iconsa[$x].': check ';
else
echo '<br>'.$iconsa[$x].': chok ';
}
If the index from the database and the array I made are the same, it will state check, else it will state chok.
$arraysAreEqual = ($a == $b); // TRUE if $a and $b have the same key/value pairs.
$arraysAreEqual = ($a === $b); // TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
taken via :
PHP - Check if two arrays are equal
I posted this in my comment, but I suppose the outline will work better in an answer.
I hope this could be of any help:
<?php
$array_a = ['test','test2']; // assume this is your first array
$array_b = ['test']; // assume this is the array you wan to compare against
$found = false;
foreach ($array_a as $key_a => $val_a) {
$found = false;
foreach ($array_b as $key_b => $val_b) {
if ($val_a == $val_b) {
echo '<br>'. $val_b .': check ';
$found = true;
}
}
if (!$found)
echo '<br>'. $val_a .': chok ';
}
?>
EDIT: Please excuse me for not testing it.
This thing will loop through the first array, and compare it with every value in the other array.
Tip: You can easily put this in a function and call it like compare($arr1, $arr2)
You can try in_array method:
$searchesa = array("google","yahoo","bing");
$iconsa = array("facebook","twitter","googleplus","linkedin","pinterest","delicious","stumbleupon","diigo",'google');
foreach($searchesa as $val){
if(in_array($val, $iconsa)){
echo "check";
} else {
echo "choke";
}
}
Note: I've added "google" in $iconsa array.
If I understand you correctly this is what you are looking for:
// Lets prepare the arrays
$searchEngines = explode(',', $searchengine);
$icons = explode(',', $icon);
// Now let's define the arrays to match with
$searchEnginesCompare = array(
'google',
'yahoo',
'bing'
);
$iconsCompare = array(
'facebook',
'twitter',
'googleplus',
'linkedin',
'pinterest',
'delicious',
'stumbleupon',
'diigo'
);
// Check the search engines
foreach ($searchEngines as $k => $searchEngine) {
if (in_array($searchEngine, $searchEnginesCompare)) {
echo $searchEngine." : check<br />";
} else {
echo $searchEngine." : failed<br />";
}
}
// Now let's check the icons array
foreach ($icons as $k => $icon) {
if (in_array($icon, $iconsCompare)) {
echo $icon." : check<br />";
} else {
echo $icon." : failed<br />";
}
}

php multidimensional array if loop

I have a multidimensional array like this
$array['value'][1][1]
Now i would like to implement if loop like this
if ($value = $array['value'][1][1]) {
echo "It works";
}
Now it works if i assign the values like [1][1],[2][1].
Is it possible to compare the whole array.
I mean if the array looks like
array[value][1][1],array[value][2][1],..........,array[value][n][1]
It works should be echoed.
I tried like this.
if ($value = $array['value'][][]) {
echo "It works";
}
But its not working. Can anyone give me the correct syntax?
I'm not sure if this is what you're looking for but you could try this function
$value is 1 in your case
function($array,$value)
foreach($array['amazon'] as $val){
if($value != $val[1])return FALSE;
}
return TRUE;
}
The function runs through $array['amazon'][*] and checks condition for each value. If found FALSE for any it returns
Based on your comments of what you're trying to accomplish, I think the following may solve your dilemma. Let me know if I'm going the wrong direction with this or have any additional questions/concerns.
<?php
$forms = array(
'amazon' => array(
0 => array(
1 => 111,
),
1 => array(
1 => 222,
),
2 => array(
1 => 333
)
)
);
$value = 333;
$it_works = False;
foreach($forms['amazon'] as $array) {
if($array[1] == $value) {
$it_works = True;
break;
}
}
if($it_works === True) {
print 'It Works!';
}
?>
You can try this:
$itWorks = true;
for( $a = 0; $a < sizeof( $array[value] ); $a ++ ){
if ( $value != $array[value][$a][1] ){
$itWorks = false;
break;
}
}
if( $itWorks ){
echo "It works";
}
Of course you must replace [value] with a legitimate value
function check() {
for($i = 0; $i < count($array[$value]); $i++) {
if($value != $array[$value][$i][1])
return FALSE;
}
echo 'It works!';
}

How to check for one and only value?

I have an switch with a random variable name and a array which can contain the values left, right, up and down.
For example:
switch ($i) {
case 0:
$name='something1';
$array=array('north', 'south', 'west');
break;
case 1:
$name='something2';
$array=array('north', 'south');
case 2:
$name='something3';
$array=array('south');
}
How can I make a script that checks for example if the only value in the array is 'south'? In my script the output will be something3, and if I check for the value's north and south, the script would output something2?
Hope you understand me. Thanks!
I would do:
if((count($array) == 1) && ($array[0] == 'south')){
//code here
}
This will only work if the array has one element.
Ok, I think this is a pretty foolproof way of accomplishing this:
<?php
function checktangent($array,$tocheck){
$tocheck = explode(',', str_replace(' ', '', $tocheck));
if(count($tocheck) == count($array)){
$foundall = true;
foreach($tocheck as $value){
if(!in_array($value, $array))
$foundall = false;
}
return $foundall;
}
else
return false;
}
//Use like:
$array = array('north', 'south', 'west');
if(checktangent($array, 'north, south'))
echo 'found';
else
echo 'not found'
?>
You can compare arrays directly in PHP. Be careful though, because this also compares the order of the values.
var_dump(array(1, 2) == array(1, 2)); //true
var_dump(array(1, 2) == array(2, 1)); //false
If you can guarantee the same order, you could do something like this:
<?php
$directions = array('north', 'south');
switch($directions) {
case array('north'):
echo 'north';
break;
case array('south'):
echo 'south';
break;
case array('north', 'south'):
echo 'north south';
break;
}
?>
http://codepad.viper-7.com/TCoiDw
This should work if I understand what your looking for correctly
if (false == count(array_diff(array('north', 'south', 'west'), $array))) {
echo 'something1';
} else if (false == count(array_diff(array('north', 'south'), $array))) {
echo 'something2';
} else if (count($array) == 1 AND current($array) = 'south') {
echo 'something3';
}
I think an easier solution would be:
array_unique($array);
if (count($array) == 1 && in_array('south', $array))
// Only south exists.

PHP If Statement with Multiple Conditions

I have a variable$var.
I want echo "true" if $var is equal to any of the following values abc, def, hij, klm, or nop. Is there a way to do this with a single statement like &&??
An elegant way is building an array on the fly and using in_array():
if (in_array($var, array("abc", "def", "ghi")))
The switch statement is also an alternative:
switch ($var) {
case "abc":
case "def":
case "hij":
echo "yes";
break;
default:
echo "no";
}
if($var == "abc" || $var == "def" || ...)
{
echo "true";
}
Using "Or" instead of "And" would help here, i think
you can use in_array function of php
$array=array('abc', 'def', 'hij', 'klm', 'nop');
if (in_array($val,$array))
{
echo 'Value found';
}
Dont know, why you want to use &&. Theres an easier solution
echo in_array($var, array('abc', 'def', 'hij', 'klm', 'nop'))
? 'yes'
: 'no';
you can use the boolean operator or: ||
if($var == 'abc' || $var == 'def' || $var == 'hij' || $var == 'klm' || $var == 'nop'){
echo "true";
}
You can try this:
<?php
echo (($var=='abc' || $var=='def' || $var=='hij' || $var=='klm' || $var=='nop') ? "true" : "false");
?>
I found this method worked for me:
$thisproduct = "my_product_id";
$array=array("$product1", "$product2", "$product3", "$product4");
if (in_array($thisproduct,$array)) {
echo "Product found";
}
Sorry to resurrect this, but I stumbled across it & believe it adds value to the question.
In PHP 8.0.0^ you can now use the match expression like so:
<?php
echo match ($var) {
'abc','def','hij','klm' => 'true',
};
?>
//echos 'true' as a string
Working link from OnlinePHPfunctions
PHP Manual
Try this piece of code:
$first = $string[0];
if($first == 'A' || $first == 'E' || $first == 'I' || $first == 'O' || $first == 'U') {
$v='starts with vowel';
}
else {
$v='does not start with vowel';
}
It will be good to use array and compare each value 1 by 1 in loop. Its give advantage to change the length of your tests array. Write a function taking 2 parameters, 1 is test array and other one is the value to be tested.
$test_array = ('test1','test2', 'test3','test4');
for($i = 0; $i < count($test_array); $i++){
if($test_value == $test_array[$i]){
$ret_val = true;
break;
}
else{
$ret_val = false;
}
}
I don't know if $var is a string and you want to find only those expressions but here it goes either way.
Try to use preg_match http://php.net/manual/en/function.preg-match.php
if(preg_match('abc', $val) || preg_match('def', $val) || ...)
echo "true"

Categories