Consider:
I have a variable called $field
that from time to time may have, among others, values such as action
, id
, and another_term
. I want to use a switch
structure to sift the values:
switch ($field) {
case 'action':
// do something
break;
case 'id':
// do something
break;
case (strpos($field, '_term')):
// do something else
break;
}
The first two cases work. The third does not. I am thinking that this is an incorrect use of a switch statement. Is this better handled as an if/else sequence?
strpos in PHP is a built-in function. Its use is to find the first occurrence of a substring in a string or a string inside another string. The function returns an integer value which is the index of the first occurrence of the string.
Switch/case string comparison is case-sensitive.
Return Value: Returns the position of the first occurrence of a string inside another string, or FALSE if the string is not found.
A case or default label can only appear inside a switch statement. The type of switch expression and case constant-expression must be integral. The value of each case constant-expression must be unique within the statement body.
You can do it using the switch
statement like this:
$field = 'bla bla_term bla';
switch (true) {
case $field === 'action':
echo 'action';
break;
case $field === 'id':
echo 'id';
break;
case strpos($field, '_term') >= 0:
echo '_term';
break;
}
The switch
statement just compares the expressions in each case
block to the value in the switch
parentheses.
Expressions are units of code that you can reduce to a value, such as 2 + 3
or strpos(...)
. In PHP most things are expressions.
Here is an annotated version of the above example:
// We are going to compare each case against
// the 'true' value
switch (true) {
// This expression returns true if $field
// equals 'action'
case $field === 'action':
echo 'action';
break;
// This expression returns true if $field
// equals 'id'
case $field === 'id':
echo 'id';
break;
// This expression returns true if the
// return value of strpos is >= 0
case strpos($field, '_term') >= 0:
echo '_term';
break;
}
If you want to use the return value of the strpos
call then you can just assign it (assignments are expressions in PHP):
case ($pos = strpos($field, '_term')) >= 0:
echo '_term at position ' . $pos;
break;
switch is just a sort of if x == y
with y being any of the matching cases.
case (strpos($field, '_term'))
would result in a -1 if match is not found or the point where "_term" was found (0 through string length -1 ) and not the field name.
If you're looking to catch anything with there phrase "_term" in the field do
$matches = array();
if(preg_match('/(.+)_term$/', $field, $matches)) {
$field = $matches[1];
}
this will replace the field value "address_term" or what ever "something_term" to just "address" or "something"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With