Why am I Getting This Kind of an Error in my PHP Website?

Here is your original PHP code with the error you mentioned (Notice: Undefined variable: errors and Warning: count(): Parameter must be an array or an object that implements Countable). The error occurs because the $errors array was not initialized at the start, and count($errors) is called without ensuring that $errors is defined.

Original Code with Error

code<?php

include("path.php");

?>

<?php

include(ROOT_PATH . "/app/database/db.php");

?>

<?php

$username = '';

$email = '';

$password = '';

$passwordConf = '';

if (isset($_POST['register-btn'])) {

// The $errors array is only initialized when the form is submitted
$errors = array();

if (empty($_POST['username'])) {
array_push($errors, 'Username is required');
}

if (empty($_POST['email'])) {
array_push($errors, 'Email is required');
}

if (empty($_POST['password'])) {
array_push($errors, 'Password is required');
}

if ($_POST['passwordConf'] !== $_POST['password']) {
array_push($errors, 'Passwords do not match');
}

if (count($errors) === 0) {
unset($_POST['register-btn'], $_POST['passwordConf']);
$_POST['admin'] = 0;
$_POST['password'] = password_hash($_POST['password'], PASSWORD_DEFAULT);
$user_id = create('users', $_POST);
$user = selectOne('users', ['id' => $user_id]);
dd($user);
} else {
// Populate form fields with previously entered values
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$passwordConf = $_POST['passwordConf'];
}
}

?>

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- Font Awesome -->
<link rel="stylesheet" href="assets/css/all.css">
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css?family=Candal|Lora&display=swap" rel="stylesheet">
<!-- Custom Styling -->
<link rel="stylesheet" href="assets/css/style.css">
<title>Register</title>
</head>

<body>

<?php include(ROOT_PATH. "/app/includes/header.php");?>

<div class="auth-content">

<form action="register.php" method="post">

<h2 class="form-title">Register</h2>

<!-- The issue occurs here if $errors isn't initialized -->
<?php if (count($errors) > 0): ?>
<div class="msg error ">
<?php foreach ($errors as $error): ?>
<li><?php echo $error; ?></li>
<?php endforeach; ?>
</div>
<?php endif; ?>

<div>
<label>Username</label>
<input type="text" name="username" value="<?php echo $username; ?>" class="text-input" />
</div>

<div>
<label>Email</label>
<input type="email" name="email" value="<?php echo $email; ?>" class="text-input">
</div>

<div>
<label>Password</label>
<input type="password" name="password" value="<?php echo $password; ?>" class="text-input">
</div>

<div>
<label>Password Confirmation</label>
<input type="password" name="passwordConf" value="<?php echo $passwordConf; ?>" class="text-input">
</div>

<div>
<button type="submit" name="register-btn" class="btn btn-big">Register</button>
</div>

<p>Or <a href="<?php echo BASE_URL . 'login.php'; ?>">Sign In</a></p>

</form>
</div>

<!-- JQuery -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/slick-1.8.1/slick/slick.min.js"></script>
<script src="assets/js/scripts.js"></script>

</body>

</html>

Explanation of the Error

  • Undefined variable: errors: This happens because $errors is only initialized inside the if (isset($_POST['register-btn'])) block. If the form hasn’t been submitted, $errors doesn’t exist, and the count($errors) call will throw this notice.
  • Warning: count(): Parameter must be an array or an object that implements Countable: The count() function requires an array or an object. If $errors is not initialized, it’s neither an array nor an object, so count() will trigger this warning.

Corrected Code

The issue you’re encountering stems from the fact that the $errors variable is not initialized properly when the form is first loaded. You should always initialize the $errors array before using it, and check for it being set before performing functions like count(). Here’s the corrected version of your code:

code<?php
include("path.php");
include(ROOT_PATH . "/app/database/db.php");

$username = '';
$email = '';
$password = '';
$passwordConf = '';

// Initialize the $errors array to avoid undefined variable warnings
$errors = array();

if (isset($_POST['register-btn'])) {

// Populate the $errors array if there are validation issues
if (empty($_POST['username'])) {
array_push($errors, 'Username is required');
}

if (empty($_POST['email'])) {
array_push($errors, 'Email is required');
}

if (empty($_POST['password'])) {
array_push($errors, 'Password is required');
}

if ($_POST['passwordConf'] !== $_POST['password']) {
array_push($errors, 'Passwords do not match');
}

// Proceed if there are no errors
if (count($errors) === 0) {
unset($_POST['register-btn'], $_POST['passwordConf']);
$_POST['admin'] = 0;
$_POST['password'] = password_hash($_POST['password'], PASSWORD_DEFAULT);
$user_id = create('users', $_POST);
$user = selectOne('users', ['id' => $user_id]);
dd($user);
} else {
// Populate form fields with previously entered values
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$passwordConf = $_POST['passwordConf'];
}
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="assets/css/all.css">
<link href="https://fonts.googleapis.com/css?family=Candal|Lora&display=swap" rel="stylesheet">
<link rel="stylesheet" href="assets/css/style.css">
<title>Register</title>
</head>
<body>

<?php include(ROOT_PATH . "/app/includes/header.php"); ?>

<div class="auth-content">
<form action="register.php" method="post">
<h2 class="form-title">Register</h2>

<!-- Display Errors -->
<?php if (count($errors) > 0): ?>
<div class="msg error">
<ul>
<?php foreach ($errors as $error): ?>
<li><?php echo $error; ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>

<div>
<label>Username</label>
<input type="text" name="username" value="<?php echo $username; ?>" class="text-input">
</div>

<div>
<label>Email</label>
<input type="email" name="email" value="<?php echo $email; ?>" class="text-input">
</div>

<div>
<label>Password</label>
<input type="password" name="password" class="text-input">
</div>

<div>
<label>Password Confirmation</label>
<input type="password" name="passwordConf" class="text-input">
</div>

<div>
<button type="submit" name="register-btn" class="btn btn-big">Register</button>
</div>

<p>Or <a href="<?php echo BASE_URL . 'login.php' ?>">Sign In</a></p>
</form>
</div>

<script src="assets/js/jquery.min.js"></script>
<script src="assets/slick-1.8.1/slick/slick.min.js"></script>
<script src="assets/js/scripts.js"></script>

</body>
</html>

PHP Errors “Undefined Variable” and “Count() Must Be an Array

One of the most common errors in PHP is the Notice: Undefined variable. This error occurs when a variable is used without being properly initialized. In the example below, the issue arises from trying to check the $errors array before it has been set, which results in the Undefined variable notice. Additionally, using count() on a variable that hasn’t been initialized as an array or object can lead to a count(): Parameter must be an array or an object that implements Countable error.

Example of the Error

code<?php
if (count($errors) > 0):
// Display errors here
endif;
?>

In the above code, if $errors hasn’t been initialized, PHP will throw the following error:

codeNotice: Undefined variable: errors in C:\xampp\htdocs\blog\register.php on line 84
Warning: count(): Parameter must be an array or an object that implements Countable in C:\xampp\htdocs\blog\register.php on line 84

Solution

  1. Always Initialize Your Variables: Before using a variable in PHP, make sure it’s initialized properly. In this case, $errors should be initialized as an empty array, so that when the script is first run, it doesn’t generate any errors.Corrected Code:code$errors = array(); // Always initialize the variable as an array
  2. Check if Variables Are Set Before Using Functions Like count(): If you’re checking an array with count(), ensure that the variable is indeed an array. If there’s a chance it might be undefined, you can use the isset() function to check if it’s set before calling count().Example:codeif (isset($errors) && count($errors) > 0) { // Display errors }

Conclusion

To avoid errors like “Undefined variable” or issues with count(), always initialize your variables. Proper initialization and checks will help ensure your PHP applications run smoothly and avoid common pitfalls.

Related blog posts