2

I'm learning PHP particularly about functions.. This question might looks silly but i want to know how below function will work..

function iterateArray($array)
{
  foreach($array as $item) {
    $newArray[] = 'Iterated: ' . $item;
}
return $newArray;
}

Here i tried to use the above function on my below code

$new = array('one', 'two', 'Three');
$myvar = iterateArray($new);

echo $myvar;
//echo $myvar[];
//echo $myvar[0];

These all effects as an error.. anyone can explain this..

Mani_k
  • 63
  • 5

2 Answers2

4

Appreciate that you are putting efforts for learning.

You are returning array() from the function.

And echo function prints strings.

for array(), use print_r()

Other things are fine.

Another suggestion:

In the function body:

function iterateArray($array)
{
  $newArray = array(); // Declare it in case user passes blank array.
// Hence no loop and return statement will return undefined variable.
// To avoid this error, use above line.  
 foreach($array as $item) {
    $newArray[] = 'Iterated: ' . $item;
}
return $newArray;
}
Pupil
  • 23,834
  • 6
  • 44
  • 66
2

Try as below :

<?php
function iterateArray($array)
{
    foreach($array as $item) {
        $newArray[] = 'Iterated: ' . $item;
    }
    return $newArray;
}



$new = array('one', 'two', 'Three');
$myvar = iterateArray($new);

print_r($myvar);
//echo $myvar[];

?>
AnkiiG
  • 3,468
  • 1
  • 17
  • 28