0
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

Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39
greenboxgoolu
  • 129
  • 2
  • 18
  • 1
    $value = substr('xcazasd123', 0, 2); $compare_array = array('ab','ax','ac'); if(in_array($value,$compare_array)){ // Run your code } Try using in array – Sanoj Sharma Sep 30 '20 at 07:19

3 Answers3

2

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

Tufail Ahmad
  • 396
  • 3
  • 15
1

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

black blue
  • 798
  • 4
  • 13
0

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

Slava Rozhnev
  • 9,510
  • 6
  • 23
  • 39