Php string to int error

PHP: Convert String to Number

While programming in PHP, there might be a situation where you have to convert a string into an integer. But we know that PHP does not need or support explicit type definition while declaring a variable. So you have to force a string to be converted into an integer.

We will look at the various ways by which a string can be converted into an integer in PHP in this article.

Why Do We Need to Convert String to Integer in PHP?

Sometimes you may need to convert a string into an integer, float or any other data type. This is because the data or values you are working on might be of a different data type. You might have an integer in a string format from the user. So you have to convert this string into a number for performing operations in the program.

Using number_format() Function

The number_format() function is an in-built method in PHP that is used for converting a string with grouped thousands. It takes 4 parameters:

string number_format ( $number, $decimals, $decimalpoint, $sep )

  • $number — This is the number to be formatted. If you don’t set any other parameters, this number will be formatted without any decimals
  • $decimals — This is the optional parameter that is used for specifying the decimals
  • $decimalpoint — This specifies the string used for mentioning the decimal point
  • $sep — This is a string specifying the thousands separator

If the method successfully converts the string, it returns the formatted number. On failure, it returns an E_WARNING error message.

number_format($string); // string into integer number_format($string,2); // string into float

Code Example:

Float Value: '.number_format($string,2); >else < echo 'Not a numaric value'; >?>
Integer Value: 25 Float Value: 25.00

Explanation:
In this program, an integer in the form of a string is assigned to a variable called $string. Then the is_numeric() checks the value of the variable and then formats it using the number_format() method. if the value is not numeric, the echo statement prints out the string “Not a numeric value”.

Using Type Casting settype()

The settype() method is used for setting the type of a variable and modify its existing type.

  • $variable – This is the variable that needs to be converted
  • $type – This is the type you want to convert the variable to
(int)$string; // string into integer (float)$string; // string into float (double)$string; // string into double

Code Example:

// Declare string value $string = '25'; $stringf = '25.99'; $stringd = '25.99'; // Check if string in numaric if (is_numeric($string))< // Convert string to integer using int type cast echo 'Integer Value: '.(int)$string; >else < echo 'Not a numaric value'; >// Check if string in numaric if (is_numeric($stringf))< // Convert string to float using float type cast echo '
Float Value: '.(float)$stringf; >else < echo 'Not a numaric value'; >// Check if string in numaric if (is_numeric($stringf))< // Convert string to float using float type cast echo '
Double Value: '.(double)$stringd; >else
Integer Value: 25 Float Value: 25.99 Double Value: 25.99

Explanation:
In this code, you can observe that typecasting is used for converting the string into an integer. After evaluating whether the given variable has a string value or not using the is_numeric method, the line echo ‘Integer Value: ‘.(int)$string; converts the string into an integer. Similarly, later on in the program, variables are converted to double and float, by mentioning the data type along with the variable name.

Читайте также:  Java stream найти первое совпадение

Using intval() and floatval() Function

The intval() function is used for returning the integer value of a variable.

It takes two parameters:

  • $var – This is the variable that you want to convert into an integer
  • $base – This optional parameter specifies the base for conversion. If $var has 0x as a prefix, 16 is taken as the base. If $var starts with 0, 8 is taken as the base

The floatval() method is used for obtaining the float value of a variable. It takes only one parameter $var, that is the value whose float value needs to be determined.

intval($string); // Convert string to integer floatval($string); // Convert string to float

Code Example:

// Declare string value $string = '25.99'; // Check if string in numaric if (is_numeric($string))< // Convert string to integer using intval function echo 'Integer Value: '.intval($string); // Convert string to float using floatval function echo '
Integer Value: '.floatval($string); >else
Integer Value: 25 Integer Value: 25.99

Explanation:
You can see that in the example, the intval() converts the value stored in the $string variable into an integer. Later the same value is converted into a float using the floatval() method.

Performing Mathematical Operations on String Value

Here, no in-built functions are used for a string to be converted to an integer.

By Adding Number «0» to String

Code Example:

Float Value: ' . ($string + 0.00); >else < echo 'Not a numaric value'; >?>
Integer Value: 25.23 Float Value: 25.23

Explanation:
This is one of the easiest ways to convert a string into an integer. In this program, 0 is added to the string, which converts it into a number. By adding the string with 0.00 the value is converted into a float. This conversion is done by PHP automatically.

By Multiply Number «1» to String

Code Example:

Float Value: ' . ($string * 1.00); >else < echo 'Not a numaric value'; >?>
Integer Value: 25.23 Float Value: 25.23

Explanation:
Another simple method for a string to be converted to an integer is by multiplying it by 1. So, the string 25.23 is multiplied by 1 to get an integer value.

Conclusion:

All these methods are applied when you get a number as a string but want to perform some mathematical operations on it. Although the intval(), float(), number_format() and type casting methods are very effective, adding 0 and multiplying 1 to a string is a very fast way to convert it into a number.

  • Learn PHP Language
  • PHP Interview Questions and Answers
  • PHP Training Tutorials for Beginners
  • Display Pdf/Word Document in Browser Using PHP
  • Call PHP Function from JavaScript
  • Call a JavaScript Function from PHP
  • PHP Pagination
  • Alert Box in PHP
  • Php Count Function
  • PHP Filter_var ()
  • PHP array_push Function
  • strpos in PHP
  • PHP in_array Function
  • PHP strtotime() function
  • PHP array_merge() Function
  • explode() in PHP
  • implode() in PHP
  • PHP array_map()

Источник

Php string to int error

Cast a string to binary using PHP < 5.2.1

I found it tricky to check if a posted value was an integer.

Читайте также:  Css text over background

is_int ( $_POST [ ‘a’ ] ); //false
is_int ( intval ( «anything» ) ); //always true
?>

A method I use for checking if a string represents an integer value.

$foo [ ‘ten’ ] = 10 ; // $foo[‘ten’] is an array holding an integer at key «ten»
$str = » $foo [ ‘ten’]» ; // throws T_ENCAPSED_AND_WHITESPACE error
$str = » $foo [ ten ] » ; // works because constants are skipped in quotes
$fst = (string) $foo [ ‘ten’ ]; // works with clear intention
?>

It seems (unset) is pretty useless. But for people who like to make their code really compact (and probably unreadable). You can use it to use an variable and unset it on the same line:

$hello = ‘Hello world’ ;
print $hello ;
unset( $hello );

$hello = ‘Hello world’ ;
$hello = (unset) print $hello ;

?>

Hoorah, we lost another line!

It would be useful to know the precedence (for lack of a better word) for type juggling. This entry currently explains that «if either operand is a float, then both operands are evaluated as floats, and the result will be a float» but could (and I think should) provide a hierarchy that indicates, for instance, «between an int and a boolean, int wins; between a float and an int, float wins; between a string and a float, string wins» and so on (and don’t count on my example accurately capturing the true hierarchy, as I haven’t actually done the tests to figure it out). Thanks!

May be expected, but not stated ..
Casting to the existing (same) type has no effect.
$t = ‘abc’; // string ‘abc’
$u=(array) $t; // array 0 => string ‘abc’ $v=(array) $u; // array 0 => string ‘abc’

Correct me if I’m wrong, but that is not a cast, it might be useful sometimes, but the IDE will not reflect what’s really happening:

class MyObject /**
* @param MyObject $object
* @return MyObject
*/
static public function cast ( MyObject $object ) return $object ;
>
/** Does nothing */
function f () <>
>

class X extends MyObject /** Throws exception */
function f () < throw new exception (); >
>

$x = MyObject :: cast (new X );
$x -> f (); // Your IDE tells ‘f() Does nothing’
?>

However, when you run the script, you will get an exception.

In my much of my coding I have found it necessary to type-cast between objects of different class types.

More specifically, I often want to take information from a database, convert it into the class it was before it was inserted, then have the ability to call its class functions as well.

The following code is much shorter than some of the previous examples and seems to suit my purposes. It also makes use of some regular expression matching rather than string position, replacing, etc. It takes an object ($obj) of any type and casts it to an new type ($class_type). Note that the new class type must exist:

Looks like type-casting user-defined objects is a real pain, and ya gotta be nuttin’ less than a brain jus ta cypher-it. But since PHP supports OOP, you can add the capabilities right now. Start with any simple class.
class Point protected $x , $y ;

public function __construct ( $xVal = 0 , $yVal = 0 ) $this -> x = $xVal ;
$this -> y = $yVal ;
>
public function getX () < return $this ->x ; >
public function getY () < return $this ->y ; >
>

$p = new Point ( 25 , 35 );
echo $p -> getX (); // 25
echo $p -> getY (); // 35
?>
Ok, now we need extra powers. PHP gives us several options:
A. We can tag on extra properties on-the-fly using everyday PHP syntax.
$p->z = 45; // here, $p is still an object of type [Point] but gains no capability, and it’s on a per-instance basis, blah.
B. We can try type-casting it to a different type to access more functions.
$p = (SuperDuperPoint) $p; // if this is even allowed, I doubt it. But even if PHP lets this slide, the small amount of data Point holds would probably not be enough for the extra functions to work anyway. And we still need the class def + all extra data. We should have just instantiated a [SuperDuperPoint] object to begin with. and just like above, this only works on a per-instance basis.
C. Do it the right way using OOP — and just extend the Point class already.
class Point3D extends Point protected $z ; // add extra properties.

Читайте также:  Selenium testing examples java

public function __construct ( $xVal = 0 , $yVal = 0 , $zVal = 0 ) parent :: __construct ( $xVal , $yVal );
$this -> z = $zVal ;
>
public function getZ () < return $this ->z ; > // add extra functions.
>

$p3d = new Point3D ( 25 , 35 , 45 ); // more data, more functions, more everything.
echo $p3d -> getX (); // 25
echo $p3d -> getY (); // 35
echo $p3d -> getZ (); // 45
?>
Once the new class definition is written, you can make as many Point3D objects as you want. Each of them will have more data and functions already built-in. This is much better than trying to beef-up any «single lesser object» on-the-fly, and it’s way easier to do.

Re: the typecasting between classes post below. fantastic, but slightly flawed. Any class name longer than 9 characters becomes a problem. SO here’s a simple fix:

function typecast($old_object, $new_classname) if(class_exists($new_classname)) // Example serialized object segment
// O:5:»field»:9: $old_serialized_prefix = «O:».strlen(get_class($old_object));
$old_serialized_prefix .= «:\»».get_class($old_object).»\»:»;

$old_serialized_object = serialize($old_object);
$new_serialized_object = ‘O:’.strlen($new_classname).’:»‘.$new_classname . ‘»:’;
$new_serialized_object .= substr($old_serialized_object,strlen($old_serialized_prefix));
return unserialize($new_serialized_object);
>
else
return false;
>

Thanks for the previous code. Set me in the right direction to solving my typecasting problem. 😉

If you have a boolean, performing increments on it won’t do anything despite it being 1. This is a case where you have to use a cast.

I have 1 bar.
I now have 1 bar.
I finally have 2 bar.

Checking for strings to be integers?
How about if a string is a float?

/* checks if a string is an integer with possible whitespace before and/or after, and also isolates the integer */
$isInt = preg_match ( ‘/^\s*(2+)\s*$/’ , $myString , $myInt );

echo ‘Is Integer? ‘ , ( $isInt ) ? ‘Yes: ‘ . $myInt [ 1 ] : ‘No’ , «\n» ;

/* checks if a string is an integer with no whitespace before or after */
$isInt = preg_match ( ‘/^5+$/’ , $myString );

echo ‘Is Integer? ‘ , ( $isInt ) ? ‘Yes’ : ‘No’ , «\n» ;

/* When checking for floats, we assume the possibility of no decimals needed. If you MUST require decimals (forcing the user to type 7.0 for example) replace the sequence:
7+(\.7+)?
with
9+\.3+
*/

/* checks if a string is a float with possible whitespace before and/or after, and also isolates the number */
$isFloat = preg_match ( ‘/^\s*(1+(\.1+)?)\s*$/’ , $myString , $myNum );

echo ‘Is Number? ‘ , ( $isFloat ) ? ‘Yes: ‘ . $myNum [ 1 ] : ‘No’ , «\n» ;

/* checks if a string is a float with no whitespace before or after */
$isInt = preg_match ( ‘/^5+(\.1+)?$/’ , $myString );

echo ‘Is Number? ‘ , ( $isFloat ) ? ‘Yes’ : ‘No’ , «\n» ;

Источник

Оцените статью