I'm learning basic PHP with a book. Inside the book I have done this example:
<?php
session_start()
if(array_key_exists("taskName", $_GET)) {
$_SESSION["taskList"][] = $_GET["taskName"];
}
$taskList= [];
if(array_key_exists("taskList", $_SESSION)) {
$taskList = $_SESSION["taskList"];
}
include "template.php";
The "include template.php" at the end of "functions.php" file is used in the book and it seems to work. But, when using in my example, the template.php which is used to be displayed the results, didn't work, here are the template.php part which uses PHP code:
<table>
<tr>
<th>Tasks</th>
</tr>
<?php foreach($taskList as $task) : ?>
<tr>
<td><?=$task?></td>
</tr>
<?php endforeach; ?>
</table>
Here are displayed errors:
Notice: Undefined variable: taskList in C:\xampp\htdocs\to-do-list\template.php on line 27
Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\to-do-list\template.php on line 27
In my understanding, the template.php isn't getting info from functions.php as the book it gets.
PHP Documentation
In this documentation above have the following example:
<?php
$a = 1;
include 'b.inc';
?>
So, b.inc will have the $a var. It's the same what happens in the book.
Your example works just fine, however since I can't think to start where is the problem exactly, I'd suggest to
session_start() line to add semicolon at the end of the line.Here is the exact code I tried and called the functions.php with and without arguments and works fine
functions.php
<?php
session_start();
if(array_key_exists("taskName", $_GET)) {
$_SESSION["taskList"][] = $_GET["taskName"];
}
$taskList= [];
if(array_key_exists("taskList", $_SESSION)) {
$taskList = $_SESSION["taskList"];
}
include "template.php";
template.php
<table>
<tr>
<th>Tasks</th>
</tr>
<?php foreach($taskList as $task) : ?>
<tr>
<td><?=$task?></td>
</tr>
<?php endforeach; ?>
</table>
When I tried below code it works fine on my computer (it produces some output).
File: first.php
<?php
$taskList = [];
$taskList[]=5;
$taskList[]=6;
include 'second.php';
?>
File: second.php
<table>
<tr>
<th>Tasks</th>
</tr>
<?php foreach($taskList as $task) : ?>
<tr>
<td><?=$task?></td>
</tr>
<?php endforeach; ?>
</table>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With