Help - Search - Member List - Calendar
Full Version: Typecasting using a variable
WorkTheWeb Forums > Webmaster Resources > PHP Help
Support our Sponsors!
Schraalhans Keukenmeester
I have a function that takes a $sourcestring and $delimiter for input
that converts the string into an array.

I want to include a third paramater that holds the preferences for the
field type of the array values.

Let's say this is the function header:

str_to_arr ($source,$delim,$preftype='ISFB')

(where I = int, S string, F float, B bool etc).

In the function I would like to cast the type like this:

[...]
$pos = strpos ($source,$delim,$offset);
$arr[] = (int) substr ($source,$offset,$pos-$offset);

But instead of writing (int) myself I'd rather use variable
substitution, have a variable $cast that holds "(int)" or "int" and then
rephrase the last line to:

$arr[] = $cast substr ($source,$offset,$pos-$offset);
or
$arr[] = ($cast) substr ($source,$offset,$pos-$offset);

Is this possible at all ? My server keeps returning a parse error:
"parse error, unexpected T_STRING in /yourscript.php line 20"

I know it is possible to invoke functions whose names are stored in a
variable, I can't see an obvious reason why this would not work. But
then again, I'm reknown for overlooking the obvious.

Tips and suggestions welcome!

Rgds
Hans

PS AFAIK there is no default function that allows programmer to convert
a delimited string to a multi-field one dimensional array, am I right in
that assumption?

Janwillem Borleffs
Schraalhans Keukenmeester wrote:
QUOTE
But instead of writing (int) myself I'd rather use variable
substitution, have a variable $cast that holds "(int)" or "int" and
then rephrase the last line to:


You can use settype() for this:

http://nl3.php.net/manual/nl/function.settype.php

Example:

function str_to_arr ($source,$delim,$preftype='') {
$types = array('I' => 'int', 'S' => 'string', 'F' => 'float', 'B' =>
'bool');
$cast = '';
if ($preftype && isset($types[$preftype])) {
$cast = $types[$preftype];
}
$arr = explode($delim, $source);

if ($cast) {
foreach (array_keys($arr) as $i) {
settype($arr[$i], $cast);
}
}
return $arr;
}

QUOTE
PS AFAIK there is no default function that allows programmer to
convert a delimited string to a multi-field one dimensional array, am
I right in that assumption?

See my example


JW


PHP Help | Linux Help | Web Hosting | Reseller Hosting | SSL Hosting
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2006 Invision Power Services, Inc.