Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP error when creating an array

Tags:

php

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! :)

like image 528
Jake2018 Avatar asked May 31 '26 00:05

Jake2018


2 Answers

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);
like image 178
Narendrasingh Sisodia Avatar answered Jun 02 '26 21:06

Narendrasingh Sisodia


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
like image 21
Fredmat Avatar answered Jun 02 '26 21:06

Fredmat