0

I'm fairly new to php and I'm having trouble understanding why this piece of code doesn't work:

foreach ($titles as $values) {
 echo '<a href="index.php">' . $values . '</a>';
}
Cristik
  • 24,833
  • 18
  • 70
  • 97
  • 1
    Check what $titles has. Use `var_dump($titles);` – Herry Potei Mar 22 '18 at 01:36
  • please check variable `$title` must have value – Lê Phi Mar 22 '18 at 01:37
  • Your $titles could be null or multi-dimensional. Use var_dump($titles) to inspect the content of $titles. And also enable error display. You may have undefined index titles. https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display – Michael Eugene Yuen Mar 22 '18 at 01:41
  • Please show us the error. If the error is not displaying, please enable "display errors" by adding `ini_set('display_errors', '1');` at the very beginning of your PHP script. – Raptor Mar 22 '18 at 01:47

1 Answers1

1
$titles=array('title1','title2','title3');
if (is_array($titles)){    
    foreach ($titles as $values) {
     echo '<a href="index.php">' . $values . '</a>';
    } 
}

Please check if your $titles is an array first with is_array().

Wils
  • 1,149
  • 6
  • 22
  • you cannot assume OP sets her `$titles` variable correctly. – Raptor Mar 22 '18 at 01:48
  • I modified the answer for this exception. – Wils Mar 22 '18 at 01:57
  • still incorrect. This code could lead to more errors. Rather than casting a variable to an array, it's better to check whether it's a valid array using `is_array()` function. – Raptor Mar 22 '18 at 02:03