Saturday, December 22, 2007

ListAppend

ListAppend is a rather simple utility function, however when you are dealing with lists, it can prove a great ally. This is a function that I pulled out of a class of list functions. I will publish the entire class once I get the individual functions published. The default delimiter for the ListAppend function is a ','. The delimiter length should be 1 character. Regardless of the size of the delimiter, the function will only use the first character.

The Function:

<php

function ListAppend($list,$value,$delimiter= ",")
{
$delimiter = substr($delimiter,1);
$nList = $list . $delimiter . $value;
return $nList;
}

?>

Usage:
StatementOutputComment
ListAppend('elem1,elem2', '' )elem1,elem2,Appended element is empty; delimiter is last character in list; list length is 2.
ListAppend('', 'elem1,elem2' )elem1,elem2List length is 2.
ListAppend("one___two", "three", "___")"one___two_three"Inserted the first character of delimiters before "three."

ListAppend works great to add values to a list. This function will default to a ',' for a delimiter!

For Example:

<?php
$list = "abcd";
$value = "Z";
echo ListAppend($list,$value);
?>


The results is 'abcd,Z'!

By sending the correct delimiter through, in this case '':

<?php
$list = "abcd";
$value = "Z" ;
echo ListAppend($list,$value,"");
?>


The results is 'abcdZ'!

3 comments:

Martijn van der Woud said...
This comment has been removed by the author.
Martijn van der Woud said...
This comment has been removed by the author.
Martijn van der Woud said...

For me, the function did not print any delimiters. I had to remove the
$delimiter = substr($delimiter,1);
line.

I also made a slight modification to make the function operate correctly on empty lists:

public static function ListAppend($list,$value,$delimiter= ",") {

if (strlen($list) > 0) {
$nList = $list . $delimiter . $value;
} else {
$nList = $list . $value;
}
return $nList;
}