Deprecated: The each() function is deprecated. This message will be suppressed on further calls in /home/zhenxiangba/zhenxiangba.com/public_html/phproxy-improved-master/index.php on line 456
PHP: settype - Manual
[go: Go Back, main page]

PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

strval" width="11" height="7"/> <serialize
Last updated: Thu, 03 May 2007

view this page in

settype

(PHP 4, PHP 5)

settype — 変数の型をセットする

説明

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

変数 var の型を type にセットします。

type の値は以下の命令のいずれかです。

  • "boolean" (または、PHP 4.2.0以降は"bool")
  • "integer" (または、PHP 4.2.0以降は"int")
  • "float" (PHP 4.2.0以降でのみ可能、古いバージョンでは、"double" を使用します)
  • "string"
  • "array"
  • "object"
  • "null" (PHP 4.2.0以降)

成功した場合に TRUE を、失敗した場合に FALSE を返します。

例 2489. settype() の例

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

settype($foo, "integer"); // ここでは、$foo は 5です (整数)
settype($bar, "string");  // ここでは、$bar は "1" です (文字列)
?>

gettype(), type-casting, type-juggling も参照ください。



add a note add a note User Contributed Notes
settype
sneskid at hotmail dot com
06-Mar-2007 07: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
10-Apr-2006 12: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
07-Dec-2005 02: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
30-Oct-2005 02: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-Oct-2005 10: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)!
26-Sep-2005 05: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-Jul-2005 11: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.
17-May-2005 04: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
14-Mar-2005 02:18
Instead of settype you could use:
<?php

$int
=593// $int is a integer

$int.="";  
James Reiher (IL)
23-Feb-2005 02: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
09-Dec-2004 10: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;
    }
24-Nov-2004 06: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
07-Sep-2003 02: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-Jul-2002 10: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
07-Aug-2001 06: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-Feb-2001 11: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.
slushpupie at hotmail dot com
23-Jul-2000 01:07
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>
support at mastebyte dot de
12-Jul-2000 04:39
Note that settype($string, "integer") will set $string to 0 if $string contains any lettery, but the function call will be TRUE
ns at canada dot com
06-May-2000 08: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.
tboothby at felfel dot com
11-Apr-2000 11:33
settype() for some reason increases the initial internal counter for the index of an array if you use<br>
settype($foo, "array");$foo[]='bar';<br>
'bar' will be stored in $foo[1].  furthermore, if you use<br>
reset($foo);$foo[]='barr';<br>
'barr' will be stored in $foo[1] again!
i'm using version 3.0.12 on linux 2.2.5-22
jeffg at NOcounterintuitive dot orgSPAM
28-Oct-1999 06:46
It's worth noting that one can neither <I>settype()</i> nor type-cast a variable as a long.  The workaround for this seems to be to use <I>pack()</i>.

strval" width="11" height="7"/> <serialize
Last updated: Thu, 03 May 2007
 
 
show source | credits | sitemap | contact | advertising | mirror sites