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:

<?php
   $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:

Read Also:  How to Generate PDF from Mysql Database using PHP?

<?php
   $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.

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.

Read Also:  Vuejs check if Element Exists Example

It works as bellows:

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

<?php  
$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 infinityknow.com 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.