Use a functions
To separate the code into individual functions.
Proper name for functions and variables
Give the exact and identifying names to your functions and variables
Avoid nested conditions
Instead of nested condition, try to use functions with return statement.
Use a PHP Built-in functions
Lets try with existing PHP functions, instead of writing your own code. Already lots of PHP Built-in function are available.
Search following URL http://php.net/manual/en/funcref.php