-2

I am trying to write my below code using foreach statement in PHP. I just started with PHP so still learning.

$myarray = array ("Hello World", "Hello Tree", "Hello, Proc!");
for($i = 0; $i < count($myarray); $i++) {
    $myarray[$i] .= " ($i)";
}

How can I do this?

leo
  • 7,598
  • 6
  • 46
  • 67
user1950349
  • 4,238
  • 16
  • 58
  • 106
  • 7
    Did you look at the manual for the function? http://php.net/manual/en/control-structures.foreach.php Maybe there is something specific from there you are having issues with? – chris85 Feb 07 '16 at 17:05
  • Possible duplicate of [How to find the foreach index](http://stackoverflow.com/questions/141108/how-to-find-the-foreach-index) – Sean Feb 07 '16 at 17:08

4 Answers4

4
 $myarray = array ("Hello World", "Hello Tree", "Hello, Proc!");
 foreach($myarray as $key => &$item) {
     $item .= " ($key)";
 }

&$item makes the $item a pointer instead of a copy of the array item. So any changes you make to $item will be reflected in the original. $key is equivalent to your array index counter $i. See the foreach reference for more information.

Achshar
  • 4,993
  • 8
  • 37
  • 70
2
$myarray = array ("Hello World", "Hello Tree", "Hello, Proc!");
$i = 0;
foreach($myarray as $arrayElement) {
    $i++; //Foreach item in the array it adds 1 to the variable i.
    $myarray[$i] = " $i"; //it sets the element[i] to the value of i
    echo $myarray[$i]; //it displays your array on the screen
}

This the the long way (but easy in my opinion) to do it, I don't recommend this way(use $key) but you can use it to store everything in a variable to know what your doing until you really understand the loop.

Robin Dirksen
  • 3,184
  • 21
  • 38
1

If you replace your FOR-loop with a FOREACH-loop, it would look like this :

$myarray = array ("Hello World", "Hello Tree", "Hello, Proc!");
foreach ($myarray as $key => $value) {
    $myarray[$key] .= " ($key)";
}

For more info on foreach, take a look at the official documentation.

John Slegers
  • 41,615
  • 22
  • 193
  • 161
1

Here is what you want .

$myarray = array ("Hello World", "Hello Tree", "Hello, Proc!");
 foreach($myarray as $key => $value) {
     $myarray[$key].= " ($key)";
 }

Explaination :

$key is equivalent your array index counter $i and $value is the value of array $myarray. For more information you can see this

Drudge Rajen
  • 6,477
  • 4
  • 20
  • 42