note 87059 added to function.settype
| From: | NWdev at osu1 dot php dot net | Date: | Mon, 17 Nov 2008 17:38:14 +0000 |
| Subject: | note 87059 added to function.settype | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-146632@lists.php.net to get a copy of this message | ||
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.
----
Server IP: 64.71.164.2
Probable Submitter: 76.22.69.123
----
Manual Page -- http://www.php.net/manual/en/function.settype.php
Edit -- https://master.php.net/note/edit/87059
Del: integrated -- https://master.php.net/note/delete/87059/integrated
Del: useless -- https://master.php.net/note/delete/87059/useless
Del: bad code -- https://master.php.net/note/delete/87059/bad+code
Del: spam -- https://master.php.net/note/delete/87059/spam
Del: non-english -- https://master.php.net/note/delete/87059/non-english
Del: in docs -- https://master.php.net/note/delete/87059/in+docs
Del: other reasons-- https://master.php.net/note/delete/87059
Reject -- https://master.php.net/note/reject/87059
Search -- https://master.php.net/manage/user-notes.php