undefined index php

3

I have this code, the fact is that in the line of $ _SESSION ['students'] I miss the error. What I want is that if that array of students does not exist that believes it, and when the program starts, since it does not exist, it gives me that error, as soon as it is created, it does not notify anything. How could I avoid it?

  

Notice: Undefined index: students in   C: \ wamp \ www \ arraySessions \ index.php on line 5

<?php
session_start();
require('recursos/funciones.php');

if (!$_SESSION['alumnos']) {
  $_SESSION['alumnos'] = [];
}

if (isset($_POST['registrar'])) {
  registrarAlumno();
}

?>

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Array Sesiones</title>
  </head>
  <body>

    <form action="<?= $_SERVER['PHP_SELF']; ?>" method="post">
      <label for="nombre">Nombre: </label>
      <input type="text" name="nombre" value="">
      <label for="apellido">Apellido: </label>
      <input type="text" name="apellido" value="">

      <input type="submit" name="registrar" value="Registrar">
      </form>

      <form  action="mostrarResultados.php" method="post">
        <input type="submit" name="cerrar" value="Cerrar">
      </form>

  </body>
</html>
    
asked by 17.01.2018 в 11:17
source

1 answer

3

As you are well indicated in a comment you can use isset() to determine if the variable exists and is not null or false

Example:

<?php
session_start();
require('recursos/funciones.php');

if (!isset($_SESSION['alumnos'])) {
  $_SESSION['alumnos'] = [];
}

if (isset($_POST['registrar'])) {
  registrarAlumno();
}

Documentation: link

    
answered by 17.01.2018 в 13:37