PHP is_numeric() Function Tutorial

beginner
19 min

PHP is_numeric() Function Tutorial

Welcome to our comprehensive guide on the PHP is_numeric() function! This tutorial is designed to help both beginners and intermediate learners understand this essential PHP function. Let's dive in!

Understanding the is_numeric() Function

The is_numeric() function in PHP is used to check whether a given variable is a number or not. This can be a string, an integer, a float, or even a boolean. Let's see how it works with different types of variables.

php
<?php $number = 123; $string = "456"; $boolean = true; if (is_numeric($number)) { echo "$number is a number."; } if (is_numeric($string)) { echo "$string is a number."; } if (is_numeric($boolean)) { echo "$boolean is a number."; } ?>

πŸ’‘ Pro Tip: Remember, the is_numeric() function considers empty strings as non-numeric.

Checking for Different Types of Numbers

The is_numeric() function can also help us differentiate between different types of numbers. Let's see how.

php
<?php $integer = 123; $float = 123.45; $hexadecimal = 0x7f; // Hexadecimal $octal = 0177; // Octal if (is_int($integer)) { echo "$integer is an integer."; } if (is_float($float)) { echo "$float is a float."; } if (is_int($hexadecimal)) { echo "$hexadecimal is an integer."; } if (is_int($octal)) { echo "$octal is an integer."; } ?>

πŸ“ Note: The is_int() function checks if a variable is an integer, while is_float() checks if a variable is a float.

Practical Application

The is_numeric() function is useful in various real-world scenarios. For instance, when handling user input, it can help ensure that only numeric data is processed.

php
<?php $user_input = "123abcd"; if (is_numeric($user_input)) { echo "Valid number."; } else { echo "Invalid input. Please enter a number."; } ?>

Quiz Time!

Quick Quiz
Question 1 of 1

What will the following code output?