[nycphp-talk] Casting and list
PUTAMARE
jeffknight at mac.com
Mon Dec 22 13:22:34 EST 2003
How about defining an array at the top of all the variables you want to
cast as an integer
$intVars = array('id', 'somenumber');
then a simple
ist($id,$name,$somenumber) = mysql_fetch_row($result);
foreach ($inVars as $iv) $$iv = (int) $$iv ;
should do the trick..
or you could make two SQL calls, one for things you want to be integers
and the other for everything else, followed by an array_map casting the
contents of the integer-only call (returned as an associative array,
mind you) to int.
$intVars = mysql_fetch_row($resultIntOnly);
$intVars = array_map('cast2int',$intVars);
foreach ($intVars as $intVarName => $intVarValue) $$intVarName = (int)
$intVarValue ;
list($name) = mysql_fetch_row($resultEverythingElse);
But I'm sure there are ways you can get really crazy:
$allVars = mysql_fetch_assoc($result);
foreach ($allVars as $allVarName => $allVarValue)
if (is_numeric($allVarValue) and (intval($allVarValue) ==
$allVarValue)) {
$$allVarName = (int) $allVarValue ;
} else {
$$allVarName = $allVarValue ;
}
providing you with the opportunity to really obfuscate your code with
$row = mysql_fetch_row($result);
foreach ($row as $key => $value) $$key = (is_numeric($value) and
(intval($value) == $value))?(int) $value:$value;
That should get the legibility fairies panties in a knot!
On Dec 22, 2003, at 10:39 AM, Hans Zaunere wrote:
>
> Good morning,
>
> I'm using list() (http://us4.php.net/list) to put the values from a
> mysql_fetch_row() call into separate variables - yes, it's trivial.
>
> However, I need some the elements to be casted to ints. I'm aware of
> the various workarounds, but what I'd really like to do is:
>
> list( (int) $id,$name, (int) $somenumber) = mysql_fetch_row($result);
>
> Of course, this throws a parse error. Is anyone aware of any clever
> tricks that keeps a nearly identical syntax? Or, maybe this could be a
> feature request (although it won't do me any good today :) What I'm
> doing now is:
>
> list($id,$name,$somenumber) = mysql_fetch_row($result);
>
> $id = (int) $id;
> $somenumber = (int) $somenumber;
>
>
> But I just don't like that, especially with tons of columns from the
> DB,
> big loops, etc...
>
> Thanks,
>
> H
> _______________________________________________
> talk mailing list
> talk at lists.nyphp.org
> http://lists.nyphp.org/mailman/listinfo/talk
>
Jeff Knight
jeff not junkmail at lushmedia.com
212/213-6558 x 203
LUSH media
110 W 40th St #1502
New York, NY 10018
More information about the talk
mailing list