PHP string to int | php cast to int

Today, We want to share with you php string to int.In this post we will show you php check if string is integer, hear for php intval vs int we will give you demo and example for implement.In this post, we will learn about PHP String Concatenation with an example.

Convert PHP string to int value

To cast a PHP string to int is quite easy. I required to use typecasting. Therefor you required to use (int) before your variable.


$variableName = (int)$stringName
$variableName = (float)$stringName

Here is an example of how to do this:

   $content_data = "8";
   $no_un = (int)$content_data;

first of all To check if the source code really works I can use the === operator. This PHP operator checks not only values but types as well. Therefor the source code should look like this bellow:

   $content_data = "8";
   $no_un = (int)$content_data;
   if ($content_data === 8) echo "String";
   if ($no_un === 8) echo "Integer";

One more question is open. What happens if our string is not a each number string. I mean there are other characters as well in the string.

Read Also:  Bootstrap Client Logo Slider Example

In this Example, the cast operation tries the good as well as can cast the string if only spaces are there or if the not valid characters are and then the number value.

It works as bellows:

  • “8” -> 8
  • “8.5” -> 8
  • “8,5” -> 8
  • “8  ” -> 8
  • ”  8  ” -> 8
  • “10test” -> 8
  • “test10” -> 0

$variable = "10";
$integer = (int)$variable;
echo "The variable $variable has converted to a number and its value is $integer.";  
echo "\n";

$variable = "8.1";
$float = (float)$variable;
echo "The variable $variable has converted to a number and its value is $float.";  

I hope you get an idea about php cast to int.
I would like to have feedback on my blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Read Also:  How to convert string number into month name in PHP

Related FAQ

Here are some more FAQ related to this Article:

  1. Read Also:  Simple jQuery Fade Effects Example
  2. Read Also:  integration Google No CAPTCHA reCAPTCHA using Laravel
  3. Read Also:  text sheet | textsheet | litanswers | textsheet alternative
  4. Read Also:  PHP Laravel 6 Session-Based Flash Message Example
  5. Read Also:  How to convert a string into number in PHP?
  6. Read Also:  Laravel Search Multiple Columns
  7. Read Also:  PHP Ajax Image Upload Resize Crop using jQuery
  8. Read Also:  Cross Header Access Control Allow Origin missing
  9. Read Also:  jQuery AJAX Submit form serialize PHP MySQLi
  10. Read Also:  Cross Header Access Control Allow Origin missing