Variable: memory space that we reference in php with a name that starts with $
for example $edad
could be a variable to save a person's age.
If you try to read (use) a variable before it has been defined, or it is outside of your scope of visibility PHP throws "Undefined variable" .
Example where $b
has not been mentioned before set used:
$a = 1;
if($a == 1){
$a = $b;
}
Example where $b
is being referenced outside its scope of visibility:
$a = 1;
if($a == 1){
$b = 10;
}
$a = $b;
With mentioning the variable, it is already defined, although in general this definition is accompanied by an initialization given that if we define a variable it is logical that it has an initial value that makes sense.
The solution is to define the variable before it is used and within the scope of visibility where example is needed: $b
before or after $a
:
$a = 1;
$b; //Acá ya queda definida pero sin valor inicial
if($a == 1){
...
$a = 1;
$b = 5; //Acá ya queda inicializada (definida + valor inicial)
if($a == 1){
...
Index : is the String that is used as a key to reference a value in an associative array. In this example, first and last name are Index of the associative array $estudiante
:
$estudiante['nombre'] = 'Juan';
$estudiante['apellido'] = "Gomez";
Undefined Index means that the string that we are passing with Index wanting to read a value from the array does not exist. In the example the Index domicilio
does not exist then $dom = $estudiante['domicilio'];
throw Undefined Index .
You can verify the existence of an Index with the function array_key_exists($index);
Offset : Similar to Index but for common arrays where the index is an integer that reflects the position (u offset in English) inside the array.
When you try to read the value of an array in a position that does not exist we have an Undefined Offset .
Example:
$arr[0] = "caballo";
$arr[1] = "tigre";
$animal = $arr[2]; // Undefined Offset
One way to avoid these errors is to verify that the index is greater than 0 and less than the number of array elements ( count($arr)
);