Categories: Development

PHP if matching conditions statements

Here are some examples to filter through strings in PHP to meet conditions.

PHP functions used during this tutorial are: substr, is_numeric, preg_replace, str_replace and trim.

Assume possible strings could be $string = "2 x Milky treat"; or $string = "Hash brown"; or $string = "-1 Fruit toast";

Here we have a trend that if it’s just one item there is no count x (2 x Milky treat), it’s just the item (Hash brown). Return or loss of item is seen as – count (-1 Fruit toast).

To get only strings that contain single items:

if (substr($string, 0, 1) == '-' || is_numeric(substr($string, 0, 1) == true){
//first character in string is either a - or a number
} else {
echo $string;
}

Get string that has the negative:

if (substr($string, 0, 1) == '-'){
 echo $string;
} else {
//first character is not a -
 }

Return the count of items strings only

if (is_numeric(substr($string, 0, 1)) !== FALSE) {
 echo $string; 
} else {
//first character is not a number
}

Get the count of items where count is greater than 5:

if (is_numeric(substr($string, 0, 1)) !== FALSE) {
    if (substr($string, 0, 1) > 5) {
        echo $string;
    } else { //first number is less than 5
    }
}

Return just the items:

if (is_numeric(substr($string, 0, 1)) !== FALSE || substr($string, 0, 1) == '-') {
    $words = preg_replace('/[0-9]+/', '', $string);//removes numbers 0-9
    $words = str_replace('x', '', $words);//removes the x
    $words = str_replace('-', '', $words);//removes the -
    echo trim($words);//trim gets rid of whitespace at start and end (not during)
} else {
    echo trim($string);
}

 

 

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago