Entry
How do create a function to process each letter of a comma separated string?
Jan 25th, 2001 20:11
Philip Olson, Aaron Sonnenshine,
Assuming a string exists such as this :
$string = 'a,b,c';
Using explode() will be quite useful for this task. Here's an example
of running a function on each letter within the string :
<?php
$string = 'a,b,c';
// Turn the string into an array which will end up looking like this :
// $array[0] = 'a';
// $array[1] = 'b';
// $array[2] = 'c';
// Note : Within explode() ',' is seperating the $string by
// the comma ( , )
$array = explode(',', $string);
// Loop through each element in the array. Foreach is great
// for looping. The manual has alternatives (using while) for
// PHP3 users (foreach is php4+)
foreach ($array as $key => $value) {
// Recreate our array and use a function on each letter (value)
// in this example, strtoupper() will uppercase the value
$array[$key] = strtoupper($value);
}
// Implode will turn the array back into a string and is
// used in similar fashion as explode.
$string = implode(',', $array);
?>
That's one way to do it and yes this is a silly example. The string
now looks like this :
$string = 'A,B,C';
Links to used and related resources :
http://www.php.net/manual/en/function.explode.php
http://www.php.net/manual/en/function.implode.php
http://www.php.net/manual/en/control-structures.foreach.php
http://www.php.net/manual/en/function.strtoupper.php
http://www.php.net/manual/en/function.array.php