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"
Related
The title might sound... trivial, but i had no idea how to name this problem in one sentence.
I have different arrays of variables in different places in my file(s)
for example:
//set1:
$a =1;$b=2;$c=3;$d=4;$e=5;
$set1 =array($a,$b,$c,$d,$e);
//set2:
$x=1;$y=2;
$set2 =array($x,$y);
Im tryin' to write a function which makes different operations based on array length.
For (simplified) example, in first case I wanna execute:
if($set1[0]){/*something*/}
if($set1[0] || $set1[1]){}
if($set1[0] || $set1[1] || $set1[2]){}
if($set1[0] || $set1[1] || $set1[2] || $set1[3]){}
if($set1[0] || $set1[1] || $set1[2] || $set1[3] || $set1[4]){}
In second case, I wanna execute
if($set2[0]){}
if($set2[0] || $set2[1]){}
I tried to write function using eval(), and it works...
function _f($array)
{
$i =-1;
$x =count($array);
$str ='';
$str2 ='';
while(++$i < $x)
{
if($i ==0){
$str .="\$array[$i]";
} else {
$str .=" || \$array[$i]";
}
$str2 .="if(".$str."){\n echo 'lol'; \n}\n\n";
}
echo "<pre>";
echo $str2;
echo "</pre>";
eval($str2);
}
_f($set1);
//output: lollollollollol (as I expected)
...but is that solution safe when user can set the variables? Are there better solutions?
It is not entirely clear what the intention of your program is because of the limitations of the input data, as mentioned in comment above (all $array entries evaluate to true).
But the following sequence, which would replace your loop, would produce the same result as the evals:
$status = false;
while(++$i < $x) {
$status = $status || $array[$i];
if ($status) echo 'lol';
}
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();
So, as the title says... any alternative to:
$valid_times = array('ever', 'today', 'week', 'month');
if (($this->_time == 'ever') OR ($this->_time == 'day'))
OR
if (in_array($this->_time, $valid_times))
??
Note: I know the mentioned above works, but I'm just looking for new things to learn and experiment with
UPDATE
Thanks for the info, but I didn't mentioned switch() as an alternative because it's not the case for my code. It has to be an if-statement, and I was wondering if exists something like:
if($this->_time == (('ever') OR ('day') OR ('month')))
What do you think? That would be a shorter way of the first if mentioned above
What about ?
$a1 = array("one","two","three");
$found = "two";
$notFound = "four";
if (count(array_diff($a1,array($found))) != count($a1))
/* Found */
Either you can use
$found = array("one","three");
if (count(array_diff($a1,$found)) != count($a1));
/* Either one OR three */
http://codepad.org/FvXueJkE
The only alternative I can think to accomplish this would be using regex.
$valid_times = array('ever','day','week','hour');
if(preg_match('/' . implode('|', $valid_times) . '/i', $this->_time)){
// match found
} else {
// match not found
}
[EDIT] Removed original answer since you've now specified you don't want to use switch.
In your updated question, you asked if something like this is possible:
if($this->_time == (('ever') OR ('day') OR ('month')))
The direct answer is 'no, not in PHP'. The closest you'll get is in_array(), with the array values in place in the same line of code:
if(in_array($this->_time, array('ever','day','month'))
PHP 5.4 has an update allows for shorter array syntax, which means you can drop the word array, which makes it slightly more readable:
if(in_array($this->_time, ['ever','day','month'])
But it is still an in_array() call. You can't get around that.
Sometime like this for in_array?
$arr = array(1, 2, 'test');
$myVar = 2;
function my_in_array($val, $arr){
foreach($arr as $arrVal){
if($arrVal == $val){
return true;
}
}
return false;
}
if(my_in_array($myVar, $arr)){
echo 'Found!';
}
Convoluted, but it is an alternative
$input = 'day';
$validValues = array('ever','day');
$result = array_reduce($validValues,
function($retVal,$testValue) use($input) {
return $retVal || ($testValue == $input);
},
FALSE
);
var_dump($result);
You could also use the switch statement.
switch ($this->_time) {
case 'ever':
case 'day':
//code
break;
default:
//something else
}
For the sake of science, it turns out you can use yield in a ternary operator, so you could put some complex evaluations in a anonymous generator, and have it yield on the first one that evaluates to true, without needing to evaluate them all:
$time = 'today';
if( (function()use($time){
$time == 'ever' ? yield true:null;
$time == 'today' ? yield true:null;
$time == 't'.'o'.'d'.'a'.'y' ? yield true:null;
})()->current() ){
echo 'valid';
}
In this case it will echo 'valid' without ever evaluating the concatenation.
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.
I remember reading a while back in regards to logical operators that in the case of OR, using || was better than or (or vice versa).
I just had to use this in my project when it came back to me, but I can't remember which operator was recommended or if it was even true.
Which is better and why?
There is no "better" but the more common one is ||. They have different precedence and || would work like one would expect normally.
See also: Logical operators (the following example is taken from there):
// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e = false || true;
// The constant false is assigned to $f and then true is ignored
// Acts like: (($f = false) or true)
$f = false or true;
They are used for different purposes and in fact have different operator precedences. The && and || operators are intended for Boolean conditions, whereas and and or are intended for control flow.
For example, the following is a Boolean condition:
if ($foo == $bar && $baz != $quxx) {
This differs from control flow:
doSomething() or die();
The difference between respectively || and OR and && and AND is operator precedence :
$bool = FALSE || TRUE;
interpreted as ($bool = (FALSE || TRUE))
value of $bool is TRUE
$bool = FALSE OR TRUE;
interpreted as (($bool = FALSE) OR TRUE)
value of $bool is FALSE
$bool = TRUE && FALSE;
interpreted as ($bool = (TRUE && FALSE))
value of $bool is FALSE
$bool = TRUE AND FALSE;
interpreted as (($bool = TRUE) AND FALSE)
value of $bool is TRUE
Source: http://wallstreetdeveloper.com/php-logical-operators/
Here is sample code for working with logical operators:
<html>
<head>
<title>Logical</title>
</head>
<body>
<?php
$a = 10;
$b = 20;
if ($a>$b)
{
echo " A is Greater";
}
elseif ($a<$b)
{
echo " A is lesser";
}
else
{
echo "A and B are equal";
}
?>
<?php
$c = 30;
$d = 40;
//if (($a<$c) AND ($b<$d))
if (($a<$c) && ($b<$d))
{
echo "A and B are larger";
}
if (isset($d))
$d = 100;
echo $d;
unset($d);
?>
<?php
$var1 = 2;
switch($var1)
{
case 1: echo "var1 is 1";
break;
case 2: echo "var1 is 2";
break;
case 3: echo "var1 is 3";
break;
default: echo "var1 is unknown";
}
?>
</body>
</html>
I know it's an old topic but still. I've just met the problem in the code I am debugging at work and maybe somebody may have similar issue...
Let's say the code looks like this:
$positions = $this->positions() || [];
You would expect (as you are used to from e.g. javascript) that when $this->positions() returns false or null, $positions is empty array. But it isn't. The value is TRUE or FALSE depends on what $this->positions() returns.
If you need to get value of $this->positions() or empty array, you have to use:
$positions = $this->positions() or [];
EDIT:
The above example doesn't work as intended but the truth is that || and or is not the same... Try this:
<?php
function returnEmpty()
{
//return "string";
//return [1];
return null;
}
$first = returnEmpty() || [];
$second = returnEmpty() or [];
$third = returnEmpty() ?: [];
var_dump($first);
var_dump($second);
var_dump($third);
echo "\n";
This is the result:
bool(false)
NULL
array(0) {
}
So, actually the third option ?: is the correct solution when you want to set returned value or empty array.
$positions = $this->positions() ?: [];
Tested with PHP 7.2.1
I don't think one is inherently better than another one, but I would suggest sticking with || because it is the default in most languages.
EDIT: As others have pointed out there is indeed a difference between the two.
There is nothing bad or better, It just depends on the precedence of operators. Since || has higher precedence than or, so || is mostly used.
Some languages use short-circuit, and others use full Boolean evaluation (if you know, this is similar to the directive $B in Pascal).
Explanations:
function A(){
...Do something..
return true;
}
function B(){
...Do something..
return true;
}
if ( A() OR B() ) { .....
In this example the function B() will never be executed. Since the function A() returns TRUE, the result of the OR statement is known from the first part without it being necessary to evaluate the second part of the expression.
However with ( A() || B() ), the second part is always evaluated regardless of the value of the first.
For optimized programming, you should always use OR which is faster (except for the case when the first part returns false and second part actually needs to be evaluated).