PHP Query - Check string character

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
Answer
Solution:
You can use array to store your keywords and then usein_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
Answer
Solution:
If this sub-string is always in the same place - easy and fast isswitch
// $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 incase
- any other situation are not possible or weird and redundant.switch
can also evaluate throughdefault
to another oneswitch
or other conditions
Answer
Solution:
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
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: cannot set properties of undefined (setting '_dt_cellindex')
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.