Warnings are the messages you will see most while learning. Each has a standard cause and a standard fix.
Undefined variable
<?php
echo $total;
Warning: Undefined variable $total in /path/to/index.php on line 2
Cause: you used a variable before giving it a value, or you mistyped its name. Fix: set the variable first, check the spelling, or use $total ?? 0.
Undefined array key
<?php
$user = ["name" => "Ana"];
echo $user["email"];
Warning: Undefined array key "email" in /path/to/index.php on line 4
Cause: the key does not exist. Fix: $user["email"] ?? "", or check with isset() or array_key_exists().
Array to string conversion
<?php
$items = ["a", "b"];
echo "Items: " . $items;
Warning: Array to string conversion in /path/to/index.php on line 4
Items: Array
Cause: you printed an array as if it were text. Fix: implode(", ", $items) or loop through it.
Trying to read a property of null
<?php
$user = null;
echo $user->name;
Warning: Attempt to read property "name" on null in /path/to/index.php on line 4
Cause: a value you expected to be an object is null (for example, nothing was found). Fix: check for null, or use the nullsafe operator: $user?->name.
A non-numeric value
<?php
echo "5 apples" + 3;
Warning: A non-numeric value encountered in /path/to/index.php on line 2
8
Fix: validate input before using it in maths.
Headers already sent
<?php
echo "Hello";
header("Location: /home");
Hello
Warning: Cannot modify header information - headers already sent by (output started at /path/to/index.php:2) in /path/to/index.php on line 3
Cause: header(), setcookie() or session_start() was called after output. Fix: move them before any output. Look for stray spaces before <?php too.
Deprecated
A message like Deprecated: ... is deprecated means a function or a way of writing will disappear. Examples are passing null to a function that expects a string (deprecated in PHP 8.1), or using ${var} inside strings (PHP 8.2).
<?php
echo strlen(null);
Deprecated: strlen(): Passing null to parameter #1 ($string) of type string is deprecated in /path/to/index.php on line 2
0
Fix: pass a real string, or handle the null first.
How to deal with them
- Read the message and the line number.
- Look at that line and the one before it.
- Fix the cause, do not hide the message.
The @ operator hides errors: avoid it
@ in front of an expression silences its warnings. It hides the problem and makes bugs hard to find.
<?php
$value = @$undefined["x"]; // hides the warning, the bug remains
var_dump($value);
NULL
Use ?? or a proper check instead.