$x = array("grapes","apples","oranges");
$y = " are fruit";
echo $x. $y;

desired output:

grapes are fruit.
apples are fruit.
oranges are fruit.

When i do this I get "Array" as the output. Do i need a function?

    <?php
    
    $x = array("grapes","apples","oranges");
    $y = " are fruit"; 
    
    foreach($x AS $value) 
    {
        echo $value.$y."<br>";
    }
    
    ?>
    

      The simplest is to loop through the array and make the concatenation:

      $size = count($x);
      for ($i = 0; $i < $size; $i++) {
      	$x[$i] .= $y;
      }

      or

      foreach ($x as $key => $value) {
      	$x[$key] = $value . $y;
      }

      You could also make the change at output:

      foreach ($x as $key => $value) {
      	echo $value . $y;
      }

        Is there no way to do it without a loop? there are so many array functions i thought there had to be a function that would do something to every element.

        the only thing i found was array_walk...which eliminates the need for the loop but it requires a function.

        oh well. at least i know now there is no function to do what i want.

        i hate writing loops.

          Is there no way to do it without a loop?

          Yes, there is no way to do it without a loop, assuming that by a loop you mean iteration or recursion.

          there are so many array functions i thought there had to be a function that would do something to every element

          Any function, be it PHP defined or user defined would use some form of iteration or recursion to solve the problem.
          You simply cant get away from it, unless you hardcode the concatenation.

          the only thing i found was array_walk...which eliminates the need for the loop but it requires a function.

          It doesnt eliminate the loop, but merely hides it.
          I didnt want to recommend that to you simply because you're just introducing an unnecessary overhead.

          i hate writing loops.

          Hardcode it then, but then you'll soon find that you prefer writing the loops.

            Originally posted by everknown

            the only thing i found was array_walk...which eliminates the need for the loop but it requires a function.

            so create it

            $x = array("grapes","apples","oranges");
            $y = " are fruit"; 
            
            array_walk($x,create_function('&$value,$key,$data','$value.=$data;'),$y);
            
              Write a Reply...