If I have a php string called $a. It can either end in a k or not end with a k.
If it ends with a k, then I want to do nothing, but if it does not end with a k then I want to add the string $b to the end. How can I recognise what the string $a ends with to do this?
$a=asdk ----> do nothing
$a=asdtt ---->add string $b(=rrk say) to make it $a=asdttrrk
Use this method:
if ($a[strlen($a) -1] !== 'k') $a .= $b;
alternative
if (substr($a, -1) !== 'k') $a .= $b;
You can access a specific character using $a[i], so the last character would be $a[strlen($a) - 1].
$last_char = $a[count($a) - 1];
if ($last_char == 'k') {
//do stuff here
}
There is also substr_compare:
// test 1
$a = "asdfasdf";
$b = "foo";
$a .= (substr_compare($a, 'k', -strlen('k'), strlen('k')) === 0) ? "" : $b;
echo $a; // asdfasdffoo
echo "\n\n";
// test 2
$a = "asdfasdkkkk";
$b = "foo";
$a .= (substr_compare($a, 'k', -strlen('k'), strlen('k')) === 0) ? "" : $b;
echo $a; // asdfasdkkkk
Try it out here.
function isLast($str) {
return $str[strlen($str)-1];
}
$string = 'abcdefghijk';
if(isLast($string) == 'k') {
echo 'true';
}
else {
echo 'false';
}
Yet another version (if you prefer using custom functions)
Related
I want to compare the prefix of two strings to know if both are the same or different. Like if the format is the same.
Assume variable A contains a string with a prefix, i want to compare if the prefix of the value of variable A is the same with a string i.e if($variableA == "che-123456") do something else do something else. The prefix CHE is what i want to compare.
I have written universal function for your question. You can use it :
function comparePrefixes($a, $b, $separator = "-", $caseSensitive = false) {
if (!$caseSensitive) {
$a = strtolower($a);
$b = strtolower($b);
}
return substr($a, 0, strpos($a, $separator)) === substr($b, 0, strpos($b, $separator));
}
// Testcases
var_dump(comparePrefixes('chE-454545', 'ChE-78623')); //true
var_dump(comparePrefixes('chE.54545', 'ChE.78623', ".")); //true
var_dump(comparePrefixes('abcd-454545', 'abcd-78623')); //true
var_dump(comparePrefixes('chE-454545', 'ChE-78623', "-", true)); //false
var_dump(comparePrefixes('che-454545', 'che-78623', "-", true)); //true
// use case
$a = "che-1234";
$b = "che-5425";
if (comparePrefixes($a, $b)) {
echo "prefixes are equal";
}
RUN CODE
Is there an elegant way to check if multiple, but not all, conditions are true out of any given number of conditions?
For example, I have three variables: $a, $b, and $c.
I want to check that any two of these are true. So the following would pass:
$a = true;
$b = false;
$c = true;
But this wouldn't:
$a = false;
$b = false;
$c = true;
Also, I may want to check if 4 out of 7 conditions were true, for example.
I realise I can check each combination, but this would get more difficult as the number of conditions increased. Looping through the conditions and keeping a tally is the best option I can think of, but I thought there may be a different way to do this.
Thanks!
Edit: Thanks for all the great answers, they're much appreciated.
Just to throw a spanner in to the works, what if the variables weren't explicit booleans?
E.g.
($a == 2)
($b != "cheese")
($c !== false)
($d instanceof SomeClass)
A "true" boolean in PHP casts to a 1 as an integer, and "false" casts to 0. Hence:
echo $a + $b +$c;
...will output 2 if two out of the three boolean variables $a, $b or $c are true. (Adding the values will implicitly convert them to integers.)
This will also work with functions like array_sum(), so for example:
echo array_sum([true == false, 'cheese' == 'cheese', 5 == 5, 'moon' == 'green cheese']);
...will output 2.
You could put your variables in an array, and use array_filter() and count() to check the number of true values:
$a = true;
$b = false;
$c = true;
if (count(array_filter(array($a, $b, $c))) == 2) {
echo "Success";
};
I'd go for a method like the following:
if (evaluate(a, b, c))
{
do stuff;
}
boolean evaluate(boolean a, boolean b, boolean c)
{
return a ? (b || c) : (b && c);
}
What it says is:
If a is True, then one of b or c must be true too to comply with 2/3
True criterion.
Else, both b and c must be true!
If you want to expand and customise the conditions and the number of variables I'd go for for a solution like the following:
$a = true;
$b = true;
$c = true;
$d = false;
$e = false;
$f = true;
$condition = 4/7;
$bools = array($a, $b, $c, $d, $e, $f);
$eval = count(array_filter($bools)) / sizeof($bools);
print_r($eval / $condition >= 1 ? true : false);
Simply we evaluate the true's and we make sure that the % of True is equals or is better than what we want to achieve. Likewise you could manipulate the final evaluation expression to achieve what you want.
This should also work, and would allow you fairly easily to adjust to the numbers.
$a = array('soap','soap');
$b = array('cake','sponge');
$c = array(true,true);
$d = array(5,5);
$e = false;
$f = array(true,true);
$g = array(false,true);
$pass = 4;
$ar = array($a,$b,$c,$d,$e,$f,$g);
var_dump(trueornot($ar,$pass));
function trueornot($number,$pass = 2){
$store = array();
foreach($number as $test){
if(is_array($test)){
if($test[0] === $test[1]){
$store[] = 1;
}
}else{
if(!empty($test)){
$store[] = 1;
}
}
if(count($store) >= $pass){
return TRUE;
}
}
return false;
}
U can use while loop :
$condition_n = "x number"; // number of required true conditions
$conditions = "x number"; // number of conditions
$loop = "1";
$condition = "0";
while($loop <= $conditions)
{
// check if condition is true
// if condition is true : $condition = $condition + 1;
// $loop = $loop + 1;
}
if($condition >= $condition_n)
{
// conditions is True
}
else
{
// conditions is false
}
I think it is a little easy and short writing when you use operator "&" , "|" like this:
$a = true;
$b = true;
$c = false;
$isTrue = $a&$b | $b&$c | $c&$a;
print_r( $isTrue );
Let check by your self :D
I'm trying to work out if one string, $a, is divisible by another, $b.
All of the examples I can find tell me to use modulus, e.g.:
if(($a %$b) == 0) : echo "Is dividible" ; endif;
However, because modulus returns the remainder of the calculation, this doesn't work if $b is larger than $a, because there's still no remainder.
How do I check divisibility where $b is sometimes (but not always) larger than $a?
why don't you do this as a function:
function isDivisible($smaller,$bigger){
//handle division by zero, and hmm.. let's cover negative numbers too
if($smaller<=0) return false;
if($smaller>$bigger) return false;
return !($bigger % $smaller);
}
The negation ! should be a working and elegant way to handle it.
How about:
echo ( ($a < $b) && (($a % $b) == 0) ) ? "Is dividible" : "Is not divisable" ;
if($a==$b)
{echo "divisible a and b are equal";
}
else if($a>$b){
if(($a %$b) == 0) : echo "Is dividible" ; endif;
}
else{
echo "\$b is either large or equal to \$a";
}
Try this it should work:
$a = 7;
$b = 14;
//echo ( ($a > $b) && ( ($a % $b) == 0) ) ? "is divisible":"no divisible";
echo ( ($a < $b) && (($b % $a) == 0) ) ? "Is dividible" : "Is not divisable" ;
You can use ternary operator as example given below
(($a%$b)==0)?echo "Is divisible": echo "not divisible";
I want to do something like this:
if( $a = 'something' && $b = substr( $a, 2 ) )
{
//do something
}
I mean, on an if condition, evaluate two conditions, and the second one passing the first assigned $a as a parameter to the second condition function substr().
It is just an example, so I don't want answers to this functionality, just generic answers.
The above code throws 'Undefined' $a, since $a is not still assigned.
I could do the next:
if( $a = 'something')
{
if( $b = substr( $a, 2 ) )
//do something
}
}
but this will make my code bigger.
Is there any way to achieve something like the first example?
Edit:
I don't want to compare. Just assign and ensure that $a and $b are not null, false, ...
Your only problem is the wrong precedence of the && and = operators. This works just fine:
if (($a = 'something') && $b = substr($a, 2))
This way, $a is undefined:
if ($a = 'something' && $b = substr($a, 2))
But if you give the = operator priority:
if (($a = 'something') && $b = substr($a, 2))
It will be set.
Moreover, you can simply write:
if( $b = substr( $a = 'something', 2 ) )
This question intrigued me along with #moonwave99 answer, so I did some testing with his last answer.
if( $b = substr( $a = NULL, 2 ) ) { echo "PASS"; } else { echo "FAIL"; }
FAIL
if( $b = substr( $a = FALSE, 2 ) ) { echo "PASS"; } else { echo "FAIL"; }
FAIL
if( $b = substr( $a = 0, 2 ) ) { echo "PASS"; } else { echo "FAIL"; }
FAIL
if( $b = substr( $a = TRUE, 2 ) ) { echo "PASS"; } else { echo "FAIL"; }
FAIL
if( $b = substr( $a = 233, 2 ) ) { echo "PASS"; } else { echo "FAIL"; }
PASS
if( $b = substr( $a = "SOMETHING", 2 ) ) { echo "PASS"; } else { echo "FAIL"; }
PASS
The only way to get it to fail was to pass the Boolean TRUE. But if you are expecting string values, it should fail all Boolean values, zero and NULL and evaluate to true on ints, floats, and string values. (Haven't tested with array, but I suspect it would fail for any non-primitive types). Interesting question.
Use isset() for that.Also keep in mind use == or === for comparison operations since = is assignment operator
if( (isset($a) && $a == 'something') && (isset($b) && $b == substr( $a, 2 )) )
{
//do something
}
I'm curious if it's possible to string along a couple possibilities for a function in an if statement, link them to a single variable and return the one that works, if any.
The following doesn't work, but it demonstrates the idea. I'd like the below to return 2 since the function myFn() only returns true when 2 is passed to it.
But instead the following returns true: 1.
if ($b = myFn(1) || $b = myFn(2) || $b = myFn(3)) {
echo 'true: ' . $b;
} else {
echo 'false: ' . $b;
}
function myFn($a) {
if ($a == 2) return $a;
return false;
}
Short of adding a series of elseifs, is there a way to string the functions in a series of ORs while only returning the successful one?
codepad: http://codepad.org/ldiCxY4j
Just wrap each assignment in parenthesis:
(($b = myFn(1)) || ($b = myFn(2)) || ($b = myFn(3)))
See: PHP operator precedence
When using logical operators, PHP coerces the result to boolean. Without the extra parens, it echoes '1' because echoing coerces true to '1'.
You may be better off using a loop:
/**
* Get the first $array value that passes the $test, or else null.
* #return mixed|null
*/
function find ($array, $test) {
foreach ($array as $index => $value) {
if (call_user_func($test, $value, $index, $array))
return $value;
}
}
For such concatenations of assignments PHP has the or operator, which is the same as || but with less precedence than =. This means that
if ($b = myFn(1) or $b = myFn(2) or $b = myFn(3))
is treated like:
if (($b = myFn(1)) or ($b = myFn(2)) or ($b = myFn(3)))
while
if ($b = myFn(1) || $b = myFn(2) || $b = myFn(3))
is treated like:
if ($b = (myFn(1) || $b = (myFn(2) || $b = myFn(3))))