Forum Moderators: coopster
<?
$my_array = array("a" => "Cat", "b" => "Dog", "c" => "Horse");
extract($my_array);
$string = "$a $b $c";
$tok = strtok($string, " \n\t");
while ($tok!== false) {
$ratter = "$tok, ";
echo $ratter ;
$tok = strtok(" \n\t");
}
?>
I basically want to make the following, notice the "$GRABVALUE", but of course it isn't going to work. The reason being, I need to include the total value in an area that will not allow php script but I can put ". GRABVALUE . " in:
<?php
$my_array = array("a" => "Cat", "b" => "Dog", "c" => "Horse");
extract($my_array);
$string = "$a $b $c";
$tok = strtok($string, " \n\t");
$GRABVALUE = (while ($tok!== false) {
$ratter = "$tok, ";
echo $ratter ;
$tok = strtok(" \n\t");
})
?>
Please help, I've been trying for the last 4 hours.
[edited by: Champak at 8:30 am (utc) on Jan. 24, 2007]
If you have an array like $my_array:
$string=implode(",",$my_array);
would produce "Cat,Dog,Horse". The first parameter can be more than one character, e.g. implode(",<br>\n",$my_array) would produce:
Cat,<br>
Dog,<br>
Horse
strtok takes two parameters, the string to tokenize and the tokens.
if you need the last text snippet, then you have it in
$ratter outside the loop
or without the last ", ":
$last = rtrim [php.net]($ratter, ", ");
or you can do the same by
$string=implode [php.net](", ",$my_array); //the space you can also insert
echo $string
last value of an array can be get by
$last = end [php.net]($my_array);
Hope this helps
<?php
$my_array = array("a" => "Cat", "b" => "", "c" => "Horse");
extract($my_array);
$string = "$a $b $c";
$tok = strtok($string, " \n\t");
$i = 0;
while ($tok!== false) {
$ratter = "$tok, ";
echo $ratter ;
$tok = strtok(" \n\t");
$i++;
}
$echo $i;
?>
How do I fix that? One last thing if it is possible, delete the last comma on the whole thing so no comma comes after the very last value in the array.
[edited by: Champak at 4:12 pm (utc) on Jan. 24, 2007]
array("a" => "Cat", "b" => "Dog", "c" => "Horse", "d" => "") into "Cat, Dog, Horse", yes? Let's begin by familiarizing ourselves with a couple of functions:
By combining them together, we get our desired result:
join(", ", array_filter(array_values(["a" => "Cat", "b" => "Dog", "c" => "Horse", "d" => ""]))) "Cat, Dog, Horse" What's happening when we do this? Let's find out, step by step:
array_values(["a" => "Cat", "b" => "Dog", "c" => "Horse", "d" => ""]) ["Cat", "Dog", "Horse", ""] array_filter(["Cat", "Dog", "Horse", ""]) ["Cat", "Dog", "Horse"] join(", ", ["Cat", "Dog", "Horse"]) "Cat, Dog, Horse" (the basic technique falls under the heading of functional programming [en.wikipedia.org] which, though often sadly cumbersome in PHP, is still something every programmer ought to know)
pinterface, that is EXACTLY what I needed, and so much easier. THANK YOU! Funny thing, I was actually messing with each of those functions on their own, but wasn't getting the desired results on either fronts, and never thought about joining them together.