Sunday, December 16, 2007

ListGetAt

ListGetAt is a really cool ColdFusion function. Is great for grabbing values from a comma separated list (or any other delimited list)! I use this function a lot instead of the explode function. They essentially do the same, but using this function removes 1 step. Instead of first exploding the then getting the value for your array key. For the seasoned PHP coder and everyone else, the position will always start at 1 NOT 0. Also, the default delimiter is a ','(comma).

The Function:

function ListGetAt($list,$position,$delimiter=",")
{
$bit = explode($delimiter,$list);
return $bit[($position-1)];
}

Usage:

Using the ListGetAt function is quite easy!

<?php
$list =
"apples,oranges,grapes";
echo ListGetAt($list,1);
?>


The resulting out put would be: apples

<?php
$list = "apples+oranges+grapes";
echo ListGetAt($list,2,"+");
?>

The resulting out put would be: oranges



2 comments:

Anonymous said...

PERFECT! Thanks for the post. I have been beating my had against the wall for an hour. I am a CF developer that gets suckered into PHP projects.

Yo said...

i prefer CF over PHP ... and just wrote my own UDF in PHP, then decided to do a quick search to see if anyone else did it and yours is essentially exactly like mine, including the variable names lol except you added a default delimiter - i like that