-1

I have built a php function to print the name of a person entered into my array, but it is not printing the names, it is only print the word . Please let me know if you can assist me with this.

<?php

$names = array(0 => array(name =>"Becky", email => "@hotmail.com"),
            1 => array(name =>"Tom", email => "@yahoo.com"),
            2 => array(name => "Milduew", email => "@google.com")
);

function printInfo() {
echo "<table>";
foreach((array) $names as $name){
   echo "<tr><td>" . $name[0]. "</td>";
   echo "<td>" . $name[1]. "</td>";
   echo "<td>" . $name[2]. "</td></tr>";
   echo"</table>";
}

 }


 printInfo();
?>

2 Answers2

1

Two main problems:

  1. Scope. $names is undefined in the scope of printInfo().

    You can alter your function to take the array as an argument.

    function printInfo($names) { ...
    

    and then call it with printInfo($names);

  2. The inner arrays in your $names array have string keys, but you are referring to numeric keys.

    You need to refer to $name['name'] and $name['email'] rather than $name[0] and $name[1]. (Incidentally, your input array only has two columns, so $name[2] would be undefined regardless.)

Also, there's no need to cast $names to an array (with (array) $names in your foreach loop), and doing so may actually cause problems. If you need to ensure that the input is an array, you can declare the type in the function definition.

function printInfo(array $names) { ...
Don't Panic
  • 41,125
  • 10
  • 61
  • 80
-1

Need to use following:

$name['name'] instead of name[0]
Maxqueue
  • 2,194
  • 2
  • 23
  • 55