0

I have the following code in my program but it is giving me an error when I include 'errors.php' in the form of my 'index.php' that I can’t solve. I had used it before and I never had this error, so I'm confused about this error. This is my code:

Index.php

<form method="post" action="register.php">
    <?php include('errors.php'); ?>
    <div class="input-group">
        <label>Título</label>
        <input type="title" name="title" value="">
    </div>
    <div class="input-group">
        <label>Difficulty</label>
        <select name="difficulty" id="difficulty">
            <option value="1">1</option>
            <option value="2">2</option>
        </select>
    </div>
    <br>
    <div class="input-group">
        <label>Solución</label>
        <textarea name="solution" rows="4" cols="55"></textarea>
    </div>

    <div class="input-group">
        <button type="submit" class="btn" name="reg_exercise">Add</button>
    </div>
</form>

Errors.php

<?php
if (isset($_SESSION["errors_reg"])) {
    $errors = $_SESSION["errors_reg"];
    $_SESSION["errors_reg"] = null;
}
?>

<?php
if (isset($_SESSION["errors_student"])) {
    $errors = $_SESSION["errors_student"];
    $_SESSION["errors_student"] = null;
}
?>

<?php  if (count($errors) > 0) : ?>
    <div class="error">
        <?php foreach ($errors as $error) : ?>
            <p><?php echo $error ?></p>
        <?php endforeach ?>
    </div>
<?php  endif ?>
<?php
$errors = null;
?>

I’m getting an error in the line <?php if (count($errors) > 0) : ?>

Can anyone tell me why this error appears? This is the error:

Warning: count(): Parameter must be an array or an object that implements Countable in C:\wamp64\www\project\errors.php on line 15  <?php  if (count($errors) > 0) : ?>
galep
  • 80
  • 7
  • [Warning: count(): Parameter must be an array or an object that implements Countable](https://stackoverflow.com/a/56011600/1255289) – miken32 May 06 '19 at 20:00

2 Answers2

1

The warning is clearly stated that the variable $errors should be array or object, you need to change your code

$errors[] = $_SESSION["errors_reg"];

and

$errors[] = $_SESSION["errors_student"];
Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20
1

As $errors is only set inside the various if conditions, it will not always be created. So first set a default to be an empty array, then at each point you add a new error, add it using []...

<?php
$errors = [];

if (isset($_SESSION["errors_reg"])) {
    $errors[] = $_SESSION["errors_reg"];
    $_SESSION["errors_reg"] = null;
}
?>
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55