if (substr('xcazasd123', 0, 2) === 'ax'){
}
Above code is working where it able to check if the "variable" is
starting with 'ax', but what if i wanted to check "multiple"
different validation ?
for example : 'ax','ab','ac' ? Without creating multiple if statement
You can use array to store your keywords and then use in_array() if you want to avoid multiple if statements.
$key_words =["ax","ab","ac"]
if (in_array( substr('yourstringvalue', 0, 2), $key_words ){
//your code
}
References:
in_array — Checks if a value exists in an array
If this sub-string is always in the same place - easy and fast is switch
// $x = string to pass
switch(substr($x,0,2)){
case 'ax': /* do ax */ break;
case 'ab': /* do ab */ break;
case 'ac': /* do ac */ break; // break breaks execution
case 'zy': /* do ZY */ // without a break this and next line will be executed
case 'zz': /* do ZZ */ break; // for zz only ZZ will be executed
default: /* default proceed */}
switch pass exact values in case - any other situation are not possible or weird and redundant.
switch can also evaluate through default to another one switch or other conditions
manual
You can use preg_match approach for test the string:
if(preg_match('/^(ax|ab|ac)/', '1abcd_test', $matches)) {
echo "String starts with: " . $matches[1];
} else {
echo "String is not match";
}
Example: PHPize.online
You can learn about PHP Regular Expressions fro more complicated string matching
Related
I cannot get my head around this. There might be a simple solution and the problem addressed already, but I could not find an answer.
<?php
$string = '';
$array = array(1, 2, 3);
foreach($array as $number) {
switch($number) {
case '1':
$string .= 'I ';
case '2':
$string .= 'love ';
case '3':
$string .= 'you';
}
}
echo $string;
?>
As you might have guessed, the sentence produced should be: I love you
But that is the actual output: I love youlove youyou
How is this even possible, when the switch is only triggered thrice.
Meanwhile I know that the problem can be fixed with a >break;< after each case. But I still do not understand why this is necessary.
I would be very happy, if someone could explain to me what PHP is doing.
Happy Valentines!
When case 1 is matched it will also execute case 2 and 3 unless there is a break.
So each time through the loop the matched case and everything following is executed.
First time: case 1, 2, 3
Second time: case 2, 3
Third time: case 3
For reference, here's an extract from the PHP documentation on switch, which explains it better than I probably would. :)
It is important to understand how the switch statement is executed in order to avoid mistakes. The switch statement executes line by line (actually, statement by statement). In the beginning, no code is executed. Only when a case statement is found with a value that matches the value of the switch expression does PHP begin to execute the statements. PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement. If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case. For example:
<?php
switch ($i) {
case 0:
echo "i equals 0";
case 1:
echo "i equals 1";
case 2:
echo "i equals 2";
}
?>
Here, if $i is equal to 0, PHP would execute all of the echo statements! If $i is equal to 1, PHP would execute the last two echo statements. You would get the expected behavior ('i equals 2' would be displayed) only if $i is equal to 2. Thus, it is important not to forget break statements (even though you may want to avoid supplying them on purpose under certain circumstances).
When you don't specify a break the code execution will fall-through to the next case.
As an example an exam paper with a score out of 10 could be graded as such:
switch ($score)
{
case 10:
// A+ when score is 10
echo 'A+';
break;
case 9:
case 8:
// A when score is 8 or 9
echo 'A';
break;
case 7:
case 6:
// B when score is 7 or 6
echo 'B';
break;
case 5:
case 4:
case 3:
// C when score between 3 and 5
echo 'C';
break;
default:
// Failed if score is less than 3
echo 'Failed';
}
I have written some code to allow calculations to be done on specific columns of data.
For example {1}*{2} would result in column 1 being multiplied by column 2. What I need to be able to do is replace these numbers with the actual values of the column.
Putting it simply I need to be able to get the value within the parenthesis, then use it like $column["value from parenthesis"] to get the value to insert into the calculation.
I can then evaluate the string.
Thanks in advance
Something like this should work:
$myString = '{1}*{2}';
$myValues = [1 => '684', 2 => '42'];
$myFormula = preg_replace_callback('{([0-9]+)}', function($match) use ($myValues) {
return $myValues[$match] ?: 'undefined';
}, $myString);
echo "Resulting formula: $myFormula";
Might want to give a harder error when an undefined index is used, but essentially this should work with some tweaking.
Also if you run a older PHP version than 5.4 you would need to rewrite the short array syntax and the lambda.
PHP Rocks !!!
$string = 'blabla bla I want this to be done !!! {10} + {12} Ah the result is awesome but let\'s try something else {32} * {54}';
// Requires PHP 5.3+
$string = preg_replace_callback('/\{(\d+(\.\d+)?)\}\s*([\+\*\/-])\s*\{(\d+(\.\d+)?)\}/', function($m){
return mathOp($m[3], $m[1], $m[4]);
}, $string);
echo $string; // blabla bla I want this to be done !!! 22 Ah the result is awesome but let's try something else 1728
// function from: http://stackoverflow.com/a/15434232
function mathOp($operator, $n1, $n2){
if(!is_numeric($n1) || !is_numeric($n2)){
return 'Error: You must use numbers';
}
switch($operator){
case '+':
return($n1 + $n2);
case '-':
return($n1 - $n2);
case '*':
return($n1 * $n2);
case '/':
if($n2 == 0){
return 'Error: Division by zero';
}else{
return($n1 / $n2);
}
default:
return 'Unknown Operator detected';
}
}
Online demo.
I'm quite used to vb.net's Select Case syntax which is essentially a switch statement, where you can do things like Case Is > 5 and if it matches, it will execute that case.
How can I do what I'm going to call "conditional switch statements" since I don't know the actual name, in PHP?
Or, what's a quick way to manage this?
switch($test)
{
case < 0.1:
// do stuff
break;
}
That's what I've tried currently.
I think you're searching for something like this (this is not exactly what you want or at least what I understand is your need).
switch (true) finds the cases which evaluate to a truthy value, and execute the code within until the first break; it encounters.
<?php
switch (true) {
case ($totaltime <= 1):
echo "That was fast!";
break;
case ($totaltime <= 5):
echo "Not fast!";
break;
case ($totaltime <= 10):
echo "That's slooooow";
break;
}
?>
I tried to add this as a comment to the answer by BoltCock, but SO is telling me that his answer is locked so I'll make this a separate (and essentially redundant) answer:
The "switch(true)" answer from BoltCock is much like the following example, which although logically equivalent to if + else if + else is arguably more beautiful because the conditional expressions are vertically aligned, and is standard/accepted practice in PHP.
But the if + else if + else syntax is essentially universal across scripting languages and therefore immediately readable (and maintainable) by anyone, which gives it my nod as well.
There is an additional way you can accomplish this, in PHP 8.0+, by using a match statement.
If you have a single expression within each case, it is equivalent to the following match statement. Note that unlike switch statements, we can choose to return a variable (in this code I am storing the result in $result).
$test = 0.05;
$result = match (true) {
$test < 0.1 => "I'm less than 0.1",
$test < 0.01 => "I'm less than 0.01",
default => "default",
};
var_dump($result);
Match statements only allow you to have a single expression after each condition. You can work around this limitation by calling a function.
function tinyCase(){}
function veryTinyCase(){}
function defaultCase(){}
$test = 0.01;
match (true) {
$test < 0.1 => tinyCase(),
$test < 0.01 => veryTinyCase(),
default => defaultCase(),
};
And for reference, if you just want to check for equality you can do:
$result = match ($test) { // This example shows doing something other than match(true)
0.1 => "I'm equal to 0.1",
0.01 => "I'm equal to 0.01",
default => "default",
};
Match statements do have some key differences from switch statements that you need to watch out for:
My last example will use a strict equality check === instead of a loose one ==.
If a default case is not provided, an UnhandledMatchError error is thrown when nothing matches.
And there is no worrying about falling through to the next case if you forget to add break.
PHP supports switch statements. Is that what you wanted?
Switch statement with conditions
switch(true)
{
case ($car == "Audi" || $car == "Mercedes"):
echo "German cars are amazing";
break;
case ($car == "Jaguar"):
echo "Jaguar is the best";
break;
default:
echo "$car is Ok";
}
I want a pattern to create a "is_id()" function to validate user input before mysql query. The pattern most contain ONLY numbers, my problem is avoid the float numbers:
function is_id($id) {
$pattern = "/^[0-9]+/";
if(preg_match($pattern,$id)) {
echo "ok";
} else {
echo "error";
}
}
is_id(0) // error
is_id(-5) // error
is_id(-5.5) // error
is_id(1.5) // ok <-- THIS IS THE PROBLEM
is_id(10) // ok
is_id("5") // ok
is_id("string") // error
$ denotes the end of a line/string to match.
/^[0-9]+$/
You're missing the trailing $ in your pattern. In is_id(1.5) your pattern is matching the 1 and stopping. If you add a trailing $ (as in ^[0-9]+$) then the pattern will need to match the entire input to succeed.
Why use a regex? Why not check types (this isn't as tiny as the regex, but it may be more semantically appropriate)
function is_id($n) {
return is_numeric($n) && floor($n) == $n && $n > 0;
}
is_numeric() verifies that it's either a float, an int, or a number than can be converted.
floor($n) == $n checks to see if it's indeed an integer.
$n > 0 checks to see if it's greater than 0.
Done...
You don't need regex for this, you can use a simple check like so:
function is_id($id)
{
return ((is_numeric($id) || is_int($id)) && !is_float($id)) && $id > -1
}
The output is as follows:
var_dump(is_id(0)); // false - are we indexing from 0 or 1 ?
var_dump(is_id(-5)); // false
var_dump(is_id(-5.5)); // false
var_dump(is_id(1.5)); // false
var_dump(is_id(10)); // true
var_dump(is_id("5")); // true
var_dump(is_id("string")); // false
I favour ircmaxell's answer.
Is it possible to use "or" or "and" in a switch case? Here's what I'm after:
case 4 || 5:
echo "Hilo";
break;
No, but you can do this:
case 4:
case 5:
echo "Hilo";
break;
See the PHP manual.
EDIT: About the AND case: switch only checks one variable, so this won't work, in this case you can do this:
switch ($a) {
case 4:
if ($b == 5) {
echo "Hilo";
}
break;
// Other cases here
}
The way you achieve this effectively is :
CASE 4 :
CASE 5 :
echo "Hilo";
break;
It's called a switch statement with fall through. From Wikipedia :
"In C and similarly-constructed languages, the lack of break keywords to cause fall through of program execution from one block to the next is used extensively. For example, if n=2, the fourth case statement will produce a match to the control variable. The next line outputs "n is an even number.". Execution continues through the next 3 case statements and to the next line, which outputs "n is a prime number.". The break line after this causes the switch statement to conclude. If the user types in more than one digit, the default block is executed, producing an error message."
No, I believe that will evaluate as (4 || 5) which is always true, but you could say:
case 4:
case 5:
// do something
break;
you could just stack the cases:
switch($something) {
case 4:
case 5:
//do something
break;
}
switch($a) {
case 4 || 5:
echo 'working';
break;
}