Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP typecasting

Tags:

types

php

casting

I was wondering what is the best way to typecast a value from one type to another.

Which variant should we use:

  1. intval($value);
  2. settype($value, 'int')
  3. (int)$value

All of them produce same result.

like image 363
s.webbandit Avatar asked Aug 08 '12 02:08

s.webbandit


People also ask

How do I cast a string in PHP?

Answer: Use the strval() Function You can simply use type casting or the strval() function to convert an integer to a string in PHP.

What is PHP type juggling?

Contrary to C, C++ and Java, type of PHP variable is decided by the value assigned to it, and not other way around. Further, a variable when assigned value of different type, its type too changes. This approach of PHP to deal with dynamically changing value of variable is called type juggling.

What is typecasting with example?

A typecast example is the transformation of an integer into a string. This could be used to compare two numbers if one is stored as a string and the other is an integer. If compatible, Java must automatically perform a conversion called Automatic Type Conversion and, if not, it must be specifically cast or converted.

How do you convert one variable type to another in PHP?

PHP settype() Function The settype() function converts a variable to a specific type.


2 Answers

(int)$value 

saves one function call compares to intval($value) and settype($value, 'int').

And (int)$value is clean enough, so I prefer this way.

When you need to use intval($value) is that when you need to use the specified base for the conversion (the default is base 10). intval accepts a second parameter for the base for the conversion.

like image 185
xdazz Avatar answered Oct 05 '22 14:10

xdazz


I prefer using

settype($value,getType(intval((int)$value))); 
like image 38
raidenace Avatar answered Oct 05 '22 14:10

raidenace