Jake2018
Jake2018

Reputation: 93

PHP error when creating an array

I apologize in advance because I am very new to programming and am in a rush to get this complete as I am running on a deadline, this is also my first time using this webpage or in fact any forum.

I am required to create a simple array and loop in PHP that stores and prints the name of 3 tennis players.

My code is as follows:

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 I run the code:

"Notice: Array to string conversion in C:\xampp\htdocs\Problem3\ProblemThree.php on line 19"

Line 19 is

echo $TennisPlayers;

And this is likely not going to be the only error once this one is corrected.

Look, I understand you aren't going to give me the direct answer to this and I appreciate that although I would really like some assistance in getting this to work. P.S Sorry for such a rookie question. Thank You! :)

Upvotes: 3

Views: 72

Answers (3)

JustLearninThisStuff
JustLearninThisStuff

Reputation: 314

You have to use print_r or var_dump if you want to show the array. You can't use echo.

 // doesn't work
echo $TennisPlayers;

// works
var_dump($TennisPlayers);

// works
echo '<pre>';
print_r($TennisPlayers);
echo '</pre>';

Upvotes: 0

Fredmat
Fredmat

Reputation: 958

You cannot print an array, you have to loop the array to get each elements:

foreach ( $TennisPlayers as $single_player ) {

    echo $single_player . '<br>';

}

This code will print:

Roger Federer
Rafael Nadal
Novak Djokovic

Upvotes: 1

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21437

Its because you can't echo an array in order to print your array you need to use print_r or var_dump. But in your case you need to show the values so you can use it as

echo implode(',',$TennisPlayers);

Upvotes: 2

Related Questions