PHP error while creating array
I apologize in advance because I am very new to programming and I am in a rush to get this completely as I am working on a deadline this is also my first time using this webpage or virtually any forum.
I need to create a simple array and loop in PHP that stores and prints the name of 3 tennis players.
My code looks like this:
html>
<head>
<title>Tennis Players Array</title>
</head>
<body>
<form action="" method="POST">
<input type="text" name="name">
<input type="submit" value = "submit">
</form>
<p>
<?php
$request = $_SERVER['REQUEST_METHOD'];
$name = $_POST['name'];
if ($request == 'GET')
{
// Do Nothing
}
else if ($request == 'POST')
{
$TennisPlayers = array("Roger Federer", "Rafael Nadal", "Novak Djokovic");
echo $TennisPlayers;
}
?>
</p>
</body>
</html>
I am getting an error when running the code:
"Note: Convert array to string in C: \ xampp \ htdocs \ Problem3 \ ProblemThree.php on line 19"
Line 19
And that probably won't be the only bug if fixed.
Look, I understand you are not going to give me a straight answer to this question, and I appreciate it, although I would really like to help him with that. PS Sorry for such a question, rookie. Thank!:)
Because you can't echo
a array
to print the array you need to use print_r
or var_dump
. But in your case, you need to show the values so that you can use them like
echo implode(',',$TennisPlayers);
You cannot print an array, you need to code the array to get each element:
foreach ( $TennisPlayers as $single_player ) {
echo $single_player . '<br>';
}
This code will print:
Roger Federer
Rafael Nadal
Novak Djokovic
You must use print_r or var_dump if you want to show the array. You cannot use echo.
// doesn't work
echo $TennisPlayers;
// works
var_dump($TennisPlayers);
// works
echo '<pre>';
print_r($TennisPlayers);
echo '</pre>';