Php text to number one

How to convert a string into a number using PHP

In most programming languages, it is a requirement to specify the data type that a variable should hold before using the variable. These data types include char, string, int, double, float, array, boolean, etc.

Some programming languages are not so strict and thus you don’t have to specify which data type it should store eg. Javascript and PHP.

For instance, in JavaScript, all you have to do is use the keywords var or let before the variable name.

In PHP, all you have to do is write a dollar sign $ followed by the variable name without having to specify the type.

However, by default, if the value of a variable is enclosed with quotes (single or double), it is considered as a string and in some languages, it will not give the desired results when used in arithmetic operations.

Example in Javascript

As you can see, in Javascript the two variables are treated as strings and their values were concatenated instead of an addition to take place. So in Javascript, you must not define numeric variables with values enclosed within quotes. Else, you will have to first use the parseInt() to convert the string into integer type or parseFloat() to convert the string into a float before attempting to perform arithmetic operations.

Читайте также:  Javascript узнать текущий адрес

In a similar way, PHP treats every value enclosed within quotes as a string. Let’s compare two numbers, one enclosed in quotes, and the other without.

Example

num1 and num2 are not identical

$num1 is considered a string while $num2 is considered an integer therefore not identical.

In PHP, we can check the data type of a variable using either the gettype() or the var_dump() function.

Example

num1 is a string
num2 is integer

However, in PHP, unlike Javascript, you can add two numbers when one is of integer type and the other a string (or both are strings) without any problem.

Example

The output is of integer type.

While strings in PHP can be converted to numbers (ie, int, float, or double) very easily, in most cases it won’t be required since PHP automatically does implicit type conversion at the time of using variables.

However, there are some instances where it may not be a good idea to wait for PHP to do the conversion for you.

For example on a parameterized PDO query, there will be a struggle sometimes for the parser to realize it is a number and not a string, and then you end up with a 0 in an integer field because you did not cast the string to an int in the parameter step.

Another scenario is when you are sending data in JSON format via an API to an app that expects it to be a number, and that is built in a language that doesn’t do implicit type conversion. This will result in an error.

Due to these, among other reasons and scenarios, you may want to do type conversion explicitly.

Methods of string to number conversion in PHP

There are multiple ways in which you can do explicit type conversion from string to number in PHP as explained below.

1. Using the settype() function

The settype() function is used to convert a variable to a specific data type.

Syntax

Parameters

Example

"; echo "The num2 type is ".gettype($num2); 

The num1 type is integer
The num2 type is double

2. Using the identity arithmetic operator

There is a little-known about and rarely used arithmetic operator in PHP called «identity», used for converting a numeric string to a number.

Syntax

All you have to do is place a plus sign + before the string numeric variable or value. It converts the number to a float and an int value.

Example

3. Cast the strings to numeric primitive data types

Typecasting is the conversion of data from one data type to another data type. You can use (int) or (integer) to cast a numeric string to an integer, or use (float), (double), or (real) to cast a numeric string to float. Similarly, you can use the (string) to cast a variable to string, and so on.

Example

"; echo "The num2 type is ".gettype($num2); 

The num1 type is integer
The num2 type is double

4. Perform math operations on the strings

In PHP, performing mathematical operations converts a numeric string to an integer or float implicitly.

You can perform operations such as ceil(), round() or floor(). However, these will round the number up or down. If you don’t want to change the value then do as below.

You can easily convert a string to a number by performing an arithmetic operation that won’t change the value such as addition with a zero (0) or multiplication by one (1).

Example

"; echo "The num2 type is ".gettype($num2); 

The num1 type is integer
The num2 type is double

5. Use intval() or floatval()

These functions intval() and floatval() can also be used to convert a numeric string into its corresponding integer and float value respectively.

Example

An advantage of this method is that you can convert multiple numeric strings in an array at once using the array_map() function which you can’t do with the other methods.

Example

array(6) < [0]=>int(23) [1]=> int(14) [2]=> int(33) [3]=> int(76) [4]=> int(29) [5]=> int(54) >
array(5) < [0]=>float(3.142) [1]=> float(10.12) [2]=> float(92.01) [3]=> float(25.98) [4]=> float(54.37) >

It’s my hope that now you can comfortably do data conversion from strings to numbers explicitly in PHP.

You May Also Like:

  • Creating and working with Strings in PHP
  • How to make multi-line Strings in PHP
  • How to check whether a String is empty in PHP
  • How to remove all spaces from a String in PHP
  • How to remove special characters from a String in PHP
  • How to do String to Array conversion in PHP
  • How to do Array to String conversion in PHP
  • How to check if a string contains a certain word/text in PHP
  • How to replace occurrences of a word or phrase in PHP string
  • Regex to remove an HTML tag and its content from PHP string
  • Variables, arrays and objects interpolation in PHP strings
  • How to insert a dash after every nth character in PHP string
  • How to change case in PHP strings to upper, lower, sentence, etc
  • Counting the number of characters or words in a PHP string

Источник

Php text to number one

Cast a string to binary using PHP < 5.2.1

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

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.

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*(9+)\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 ( ‘/^7+$/’ , $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+(\.2+)?
with
5+\.2+
*/

/* checks if a string is a float with possible whitespace before and/or after, and also isolates the number */
$isFloat = preg_match ( ‘/^\s*(6+(\.7+)?)\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 ( ‘/^2+(\.4+)?$/’ , $myString );

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

Источник

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