PHP Doku:: Legt den Typ einer Variablen fest - function.settype.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzVariablen- und typbezogene ErweiterungenVariablenbehandlungFunktionen zur Behandlung von Variablensettype

Ein Service von Reinhard Neidl - Webprogrammierung.

Funktionen zur Behandlung von Variablen

<<serialize

strval>>

settype

(PHP 4, PHP 5)

settypeLegt den Typ einer Variablen fest

Beschreibung

bool settype ( mixed &$var , string $type )

Legt den Typ der Variablen var als type fest.

Parameter-Liste

var

The variable being converted.

type

Mögliche Werte für type sind:

  • "boolean" (oder seit PHP 4.2.0 "bool")
  • "integer" (oder seit PHP 4.2.0 "int")
  • "float" (erst seit PHP 4.2.0 möglich, benutzen Sie bei älteren Versionen die veraltete Variante "double")
  • "string"
  • "array"
  • "object"
  • "null" (seit PHP 4.2.0)

Rückgabewerte

Gibt bei Erfolg TRUE zurück. Im Fehlerfall wird FALSE zurückgegeben.

Beispiele

Beispiel #1 settype()-Beispiel

<?php
$foo 
"5bar"// string
$bar true;   // boolean

settype($foo"integer"); // $foo ist jetzt 5   (integer)
settype($bar"string");  // $bar ist jetzt "1" (string)
?>

Anmerkungen

Hinweis:

Maximum value for "int" is PHP_INT_MAX.

Siehe auch


24 BenutzerBeiträge:
- Beiträge aktualisieren...
contact[at]covac-software[dot]com
28.08.2010 23:17
With reply to Chris Sullins and Michael Benedict, I don't find this behavior strange:

<?php
 
echo var_dump( (int)'' );                    // int(0)

 
echo var_dump( (float)array('a'=>'b') );    // float(1)
?>

This is due to the fact that an uninitialized variable is null, which converts to a 0. As does boolean false or an empty string or array.
When a value is not empty, such as my above array, it is converted to a 1 (integer/float) or true (boolean).
When changing between arrays and objects, it of course made sense to keep the fields intact (array key/values and object properties/values).

Cheers,
Chris.
Chris Sullins
19.04.2010 8:59
settype() has some really strange, potentially buggy behavior.

As noted by Michael Benedict, using settype() on a variable will initialize that variable.  What is stranger is that using settype() on an uninitialized variable that you are treating as an array or object will also initialize the variable.  So:

<?php
settype
($foo->bar,"integer"); // stdClass Object ( [test] => 0 )
?>

This works for a chain of any length: $foo->bar['baz']->etc

Next we look at what happens if $foo is already set.

<?php
$foo
= false;
settype($foo->bar,"integer"); // stdClass Object ( [test] => 0 )
?>

In and of itself, this wouldn't be problematic.  It might even make sense.  But in all other cases where $foo is defined, even if (boolean) $foo === false, it will throw an error unless $foo->bar is valid (i.e. $foo is an object already).

<?php
$foo
= true;
settype($foo->bar,"integer"); // Notice: Trying to get property of non-object
?>
michaltrutman at centrum dot cz
3.02.2009 17:32
You can change variable type also in another way instead of using function settype().

<?PHP
$a
= '125'; //$a is string
var_dump($a);

$a *= 1; //this convert $a to integer
var_dump($a);

$a *= 1.0; //$a is converted to float
var_dump($a);

$a .= ''; //now $a is string again
var_dump($a);

$a = NULL; //and finally $a is null
var_dump($a);
?>

With this you can easily change variable type to string, float or integer (but you can't change float to integer).

Positive side effect of this is that it is about 50% faster than using settype() function. This is because simple expression is executed more quickly than function.
NWdev
17.11.2008 18:38
In trying to convert an array of strings to an array of ints,
I attempted to use settype with array_walk.

<?php
//$numArray is generated by another process
$numArray = array('13','14','33');

var_dump($numArray);

//my conversion function
function str_to_int($val){
 
//remember: settype($x, 'int') returns boolean (1=success, 0=failure)
  //--> so return $x to return new value
   
settype($val,'int');
    echo
"<br />gettype = ".gettype($val)."<br />";
    return
$val;
}

array_walk($numArray,'str_to_int');

var_dump($numArray);
?>

The var_dumps both return the following:
<?php
array(3) { [0]=> string(2) "13" [1]=> string(2) "14" [2]=> string(2) "33" }
?>

The gettype echo will show the value as an integer.

So it seems that settype($val,'int') makes the conversion,
but the function return value remains a string.
Since settype returns a boolean, using
<?php $val = settype($val, 'int'); ?>
is not a option.

I resolved my array value conversion using this instead:
<?php
$numArray
=
     
array_map(create_function('$value', 'return (int)$value;'),$numArray);
?>
Thanks to the posting here:
http://usrportage.de/archives/
808-Convert-an-array-of-strings-into-an-array-of-integers.html

Perhaps this will save someone else spinning wheels a bit.

Also thanks to robin at barafranca dot com for
pointing out the boolean return value of settype.
mtinsley at dallasairmotive dot com
22.06.2008 22:36
Yes, just look for the ampersand (&) in the function signature. Here you see:

bool settype  ( mixed &$var  , string $type  )

There is an & before the first parameter ($var). This means the variable is passed in by reference. So the function is working with the original variable and not a copied local version. You will see this in other php functions such as asort();

References Explained: http://us3.php.net/manual/en/language.references.php
robin at barafranca dot com
5.03.2008 13:20
Just a quick note, as this caught me out very briefly:

settype() returns bool, not the typecasted variable - so:

$blah = settype($blah, "int"); // is wrong, changes $blah to 0 or 1
settype($blah, "int"); // is correct

Hope this helps someone else who makes a mistake.. ;)
andrey at php dot net
17.07.2007 19:11
Possible value is "unicode" starting PHP6.
sneskid at hotmail dot com
5.03.2007 23:57
In response to the guy who was having troubles with leading zeros and wrote the convertToInt function.

I benchmarked it and it is faster to just use base_convert than ltrim & friends.

base_convert also has a lower "first time call" cost than ltrim (this could be related to server settings).
It's about 2/3 that of ltrim.

If you only use this type of conversion once per script then it's far more beneficial to use base_convert.

The average values listed are ignoring the first time call costs.
<?php

$t
= '0100';

// avg: 0.0000025 (0.0000036 wrapped as a function)
$x = base_convert($t, 10, 10);

// avg: 0.0000028 (0.0000039 wrapped as a function)
$x = 0+ltrim($t,'0');
?>
ludvig dot ericson gmail.dot com
9.04.2006 17:36
To matt:
This function accepts a paremeter, which does not imply you using hardcoded stuff, instead you can let the user choose! \o/

As a part of a framework or something.

Plus, you can probably call this with call_user_func
matt at mattsoft dot net
7.12.2005 6:49
using (int) insted of the settype function works out much better for me. I have always used it. I personally don't see where settype would ever come in handy.
Michael Benedict
29.10.2005 19:55
note that settype() will initialize an undefined variable.  Therefore, if you want to preserve type and value, you should wrap the settype() call in a call to isset().

<?php
settype
($foo, "integer");
echo(
"|$foo|");
?>

prints "|0|", NOT "||".

To get the latter, use:
<?php
if(isset($foo)) settype($foo, "integer");
echo(
"|$foo|");
?>

25.10.2005 15:30
James Reiher (IL) writes:
23-Feb-2005 06:50

$agentnum = "007";
$agentnum = settype($agentnum, "int");
echo $agentnum; // will show up as 1 instead of 7!

James, the return value of settype function is boolean, 1 if succsess.
Correct code: $success=settype($agentnum, "int");
The $agentnum is now 7 (not 007 or not 1)!

25.09.2005 22:24
In response to the comment by Neoja regarding validating every variable in the URL using settype -- that is wrong.

All value passed in the URL are strings, even if they are numbers. (Remember, they are passed in the header, which is a specially formatted string).
nospamplease at veganismus dot ch
22.07.2005 16:38
you must note that this function will not set the type permanently! the next time you set the value of that variable php will change its type as well.

16.05.2005 21:22
I needed to pull a zerofilled integer out of a MySQL table and increment it by a certain amount.  Unfortunately, PHP treated this integer as if it were a string when I tried to add an amount to it.  For instance:

<?php
$a
= '0100';
$b = $a + 1;
print
$b;
// This would print 64 instead of 101.
?>

To fix this I created a simple function:

<?php
function convertToInt($string) {
   
$y = ltrim($string, '0');
   
$z = 0 + $y;
    return
$z;
}
// Now I can add any integer to my converted integer
$a = '0100';
$b = 2 + convertToInt($a);
print
$b;
// This prints 102
?>
reinier_deblois at hotmail dot com
13.03.2005 18:18
Instead of settype you could use:
<?php

$int
=593// $int is a integer

$int.="";   // $int is now a string
James Reiher (IL)
23.02.2005 6:50
I had a problem with PHP destroying the value of my integer with leading zeros as follows:

$agentnum = "007";
$agentnum = settype($agentnum, "int");
echo $agentnum; // will show up as 1 instead of 7!

Oddly enough, this works fine, (at least for PHP 4.3):
$agentnumber = "007";
$agentnumber += 0; // convert $number to numeric type
echo $agentnumber; // will now show up as 7!

If you do this for gods sake leave a comment on the line because its definitely not by-the-book coding. Another commentor here has used regular expressions to weed out the leading zeros, so I know its not the only solution.

I also tried the equivelant of:
$agentnum = "007";
$agentnum = (int)$agentnumber;
echo $agentnum;

But the result is a nonsense number, probably by using the concatenation of the ASCII codes as the integer.
memandeemail at gmail dot com
9.12.2004 14:17
/**
    * @return bool
    * @param array[byreference] $values
    * @desc Convert an array or any value to Escalar Object [not tested in large scale]
    */
    function setobject(&$values) {
        $values = (object) $values;
        foreach ($values as $tkey => $val) {
            if (is_array($val)) {
                setobject($val);
                $values->$tkey = $val;
            }
        }
        return (bool) $values;
    }

23.11.2004 22:34
in PHP3 converting a string to any number results in the value becoming 0.  To check if a string represents a number try this:
<PRE>
$test = "0001";
$testcp = $test;
settype($testcp,"double");

if (strval($testcp) === $test) {
   echo("\$test is a number");
} else {
   echo ("\$test is not a number");
}
</PRE>
sdibb at myway dot com
7.09.2003 7:03
Using settype is not the best way to convert a string into an integer, since it will strip the string wherever the first non-numeric character begins.  The function intval($string) does the same thing.

If you're looking for a security check, or to strip non-numeric characters (such as cleaning up phone numbers or ZIP codes),  try this instead:

<?
     $number
=ereg_replace("[^0-9]","",$number);
?>
djworld at php dot net
17.07.2002 15:02
Usually it won't be necessary to use this function, but some times you need to be sure the variables are of some kind. For example, if you send a number to a database query from a variable passed by GET or POST, you may get sure it's a number by doing SetType ($var, 'integer'); so you can avoid security holes if it isn't a number and you don't need to addslashes() it, or for example, if you need to be sure that a number won't have any decimals after rounding it, you may do the same and as it will be an integer, it won't contain decimals.

(ed: change to reflect deleted of other notes)
r dot schechtel at web dot de
6.08.2001 23:59
To: neoja@hotmail.com

I believe in this case testing the $id using is_numeric() would be the better solution.

E.g something like this:

<?php
 
if (is_numeric($id)) {
 
$db->query($sql);
 }
?>

Roman Schechtel
neoja at hotmail dot com
18.02.2001 3:42
It is always good to validate all the variables that are given in the url and would cause an error if they are of wrong type. For example, if your page is products.php?id=123 then run settype($id, "integer") in the script, before getting the product info from the database. If the user enters a non-numeric value in the url -- either pasting it wrong or intentionally :) -- the $id will be set to zero and database query will have no errors.
ns at canada dot com
6.05.2000 1:38
This settype() behaviour seems consistent to me. Quoting two sections from the manual:

"When casting from a scalar or a string variable to an array, the variable will become the first element of the array: "
<pre>
2 $var = 'ciao';
3 $arr = (array) $var;
4 echo $arr[0];  // outputs 'ciao'
</pre>

And if (like your code above) you do a settype on an empty variable, you'll end up with a one element array with an empty (not unset!) first element. So appeanding to it will start appending at index 1. As for why reset() doesn't do anything:

"When you assign a value to an array variable using empty brackets, the value will be added onto the end of the array."

It doesn't matter where the array counter is; values are added at the end, not at the counter.



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)