Thursday, 30 August 2018

PHP foreach loop does not work

I have following multiple select element in my html form (method - post). I want to convert $songs array to convert in ordered list.

<select name="songs" multiple>
  <option>song 1</option>
  <option>song 2</option>
  <option>song 3</option>
  <option>song 4</option>
  <option>song 5</option>
  <option>song 6</option>
  <option>song 7</option>
  <option>song 8</option>
  <option>song 9</option>
  <option>...</option>
</select>

I written following php code
 $songs = test_input($_POST["songs"]);
 foreach ($songs as $song)
 {
   $songs .= "<li>$song</li>";
 };

 $songList = "Songs: <ol> $songs </ol> \r\n";
 echo $songList;

 function test_input($data)
 {
      $data = trim($data);
      $data = stripslashes($data);
      $data = htmlspecialchars($data);
      return $data;
 }

But it gives me an error Invalid argument supplied for foreach()
Someone please tell what's going wrong with this foreach() loop

If function test_input() returns String instead of Array then what should I do to convert $songs into ordered list?

The following should work:
<?php
$songs = $_POST["songs"];
//$songs = Array("one","two","three");
foreach ($songs as $song)
{
   $songStr = test_input($song);
   $songsOut .= "<li>$songStr</li>";
};

$songList = "Songs: <ol> $songsOut </ol> \r\n";
echo $songList;

function test_input($data)
{
   $data = trim($data);
   $data = stripslashes($data);
   $data = htmlspecialchars($data);
   return $data;
}

?>

The test_input() needs to be called separately on each item in the array, rather than on the array itself.
Are you sure that the post data actually is an array? I tested my code with a get string (so I could type it in the browser bar), and it requires the following syntax:
http://localhost/songs.php?songs[]=one&songs[]=two&songs[]=three

The foreach error message will account for the $POST associate array not returning an array of values, uncommenting the second line in my code will help debug this. If you post the code that generates the $POST we can check that also!
Edit - changing the name of the multiple select element seems to work for me:
<select name="songs[]" multiple>
  <option>song 1</option>
  <option>song 2</option>
  <option>song 3</option>
  <option>...</option>
</select>

see: Multi-select to Array

0 comments:

Post a Comment