3

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

3
  • What is your question? Commented May 30, 2015 at 10:18
  • You are trying to print array as string that why you getting this error. If you want to print array than used print_r($array); or var_dump($array); Commented May 30, 2015 at 10:21
  • 1
    echo implode(', ',$TennisPlayers); Commented May 30, 2015 at 10:23

3 Answers 3

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

(FYI:You can accept or upvote an answer which helps you to solve your problem)
1

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

Comments

0

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>';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.