PHP – Check if a number is Even, Odd, or multiple of another

While coding PHP applications, there are times when we need to check if a number is even, odd, or multiple of another.

Here are a few methods to do the same.

Method 1:

$number = 3;
if($number & 1){
    echo 'Odd number!';
}else{
    echo 'Even number!';
}

Method 2:

$number = 3;
if($number % 2){
    echo 'Odd number!';
}else{
    echo 'Even number!';
}

Method 3:

$number = 3;
echo ($number % 2 ? 'Even' : 'Odd');

Method 4:

Check if the number is multiple of another. This can be used to float DIV elements and remove margin from the last ones.

for ($i=1; $i <= 10; $i++) {
	if($i % 2){
		echo $i.' is not multiple of 2';
	}else{
		echo $i.' is multiple of 2';
	}
	echo '<br />'; // Adds a line break.
}

If you know of another method, do share these in the comments.

contact us

get information for your project.

Change WordPress Excerpt Length

You can add the following code in your theme’s functions.php file to change the WordPress excerpt length. Change the number (100) to the desired length.

add_filter('excerpt_length', 'new_excerpt_length');
function new_excerpt_length($length) { return 100; }
contact us

IOGOOS WordPress development services

How-to: Get Current Url in PHP with or without Query String

In each PHP website, we need to find out the current URL of the page, and here’s the PHP code to find out the current URL of the page a user is browsing with or without the query string.

function currentUrl( $trim_query_string = false ) {
    $pageURL = (isset( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] == 'on') ? "//" : "//";
    $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
    if( ! $trim_query_string ) {
        return $pageURL;
    } else {
        $url = explode( '?', $pageURL );
        return $url[0];
    }
}

I like to keep such functions in a helpers class so I can use them anywhere in the app. To use it in a PHP class you can use the following code:

public function currentUrl( $trim_query_string = false ) {
    $pageURL = (isset( $_SERVER['HTTPS'] ) && $_SERVER['HTTPS'] == 'on') ? "//" : "//";
    $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
    if( ! $trim_query_string ) {
        return $pageURL;
    } else {
        $url = explode( '?', $pageURL );
        return $url[0];
    }
}
Contact Us

Our Services

Enquiry Now

When We Work Together

We can create something incredible

arrow
HQ INDIA
HQ INDIA
C-31, Milap Nagar,
Uttam Nagar, New Delhi,
Delhi 110059
USA
USA
6715 Backlick Rd Suite 202
Springfield,
VA 22150, USA
AUSTRALIA
AUSTRALIA
2/51, Lane Cres,
Reservoir, VIC
3037, Australia
CANADA
CANADA
61 Payzant Bog Road, Falmouth, NS, B0P 1P0, CANADA
UK
UK
3rd Floor, 131 City Road, London, EC1V 2NX, United Kingdom
UAE
UAE
Boutik Mall, Al Reem Island - Abu Dhabi, UAE
X

Let Us Call You Back

  • India+91
  • United States+1
  • United Arab Emirates+971

Your phone number is kept confidential
and not shared with others.