How to check for one and only value? - php

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.

Related

Detect which condition is false in multiple if statement

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

Compare two arrays and echo difference

What is wrong with this code? I've tried using array_udiff without any success.
<?php
#I want to echo values of $paths1 that do not appear (even partially) on $paths2.
$paths1 = array('one', 'two', 'three');
$paths2 = array('twenty one', 'twenty two');
foreach ($paths1 as $path1)
{
foreach ($paths2 as $path2)
{
if (stripos($path1, $path2) == False)
{
echo $path1 . "<br>";
break;
}
}
echo "<br>";
}
?>
You need to use stripos() === false, as if they match it's going to return 0 which is == to false.
You have your parameters mixed, it should be stripos($path2, $path1).
You need to check all values in $paths2 until you find one it is in. You are saying it's not in any $paths2 after the first one you don't find it in. Set a flag of $flag = true; between the foreach() loops. Instead of echoing inside the second foreach, just set $flag == false if stripos($path2, $path1) !== false. After the second loop ends, but before the first, output if $flag == false.
ie
foreach ($paths1 as $path1)
{
$flag = true;
foreach ($paths2 as $path2)
{
if (stripos($path2, $path1) !== false)
{
$flag = false;
break;
}
}
if($flag)
echo $path1;
}
Note: didn't test it, but should work.
The arguments to stripos are backwards. Instead of:
if (stripos($path1, $path2) == False)
You want:
if (stripos($path2, $path1) === false)

if-statement PHP using multiple strings

How can I use two or more strings?
This is what I'm using to do just one string.
if ($input == "test")
{
echo "$imput is equal to test.";
}
If I understand you correctly, something like this might work best if you have many strings to compare with.
$string = array("foo", "bar", "hello", "world");
foreach ($string as $s) {
if ($input == $s) {
echo "$input is equal to $s";
break;
}
}
I think this is what you're looking for:
if ($input == "test" && $input2 == "hello")
{
echo "$input is equal to test and input2 is equal to hello.";
}
Do you mean how can you check if two strings contain a certain value?
If so, just use &&:
if($input == "test" && $input2 == "test") {
Then you can use
foreach ($dataarray as $string) {
if ($input == $string) {
echo "Match Found";
break;
}
}
Then it results Match Found if it founds the string in the array $dataarray();

If GET query contains keywords from array

I want to make a PHP script that takes a PHP GET variable $_GET[q] made up of many different words or terms and checks to see if it contains any "keywords" that are stored in an array. An example of this would be It could look like "What time is it in San Francisco". I would want the script to pick up on "time" and "san francisco" as an example. I have played about with using
if(stripos($_GET[q],'keyword1','keyword2'))
but haven't had much luck.
Does anyone know how I could do this?
I hope everyone can understand what I am trying to describe.
You can make an array of keywords, then loop though until you find a match.
$array = array('keyword1', 'keyword2');
$found = false;
foreach($array as $x){
if(stripos($_GET['q'], $x) !== false){
$found = true;
break;
}
}
if($found){
}
UPDATE: If you want to match ALL keywords, you can do this instead:
$array = array('keyword1', 'keyword2');
$found = true;
foreach($array as $x){
$found &= stripos($_GET['q'], $x) !== false;
}
if($found){
}
DEMO: http://codepad.org/LaEX6m67
UPDATE 2: Because I'm crazy and like one-liners, you can do this in PHP 5.3+:
$array = array('keyword1', 'keyword2');
$val = $_GET['q'];
$found = array_reduce($array, function($x, $v) use($val){
return $x && stripos($val, $v) !== false;
}, true);
if($found){
}
DEMO: http://codepad.viper-7.com/Y48sHR
foreach($arr as $value){
if(stripos($_GET[q],$value){
do stuff
}
}
Use in_array function:
// assuming $arr is your array of keywords
if (in_array($_GET['q'], $arr))
echo "found a match\n";
EDIT: Based on your comments here is the code you can use, that works without any loop:
$arr = array('keyword1', 'keyword2', 'keyword3');
$brr = array_map(create_function('$m', 'return "/\b" . $m . "\b/";'), $arr);
if ($_GET['q'] !== preg_replace($brr, '', $_GET['q']))
echo "found a match\n";
else
echo "didn't find a match\n";

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