Array generates error "Undefined offset"

1

Good afternoon I'm finalizing a script that will make some updates on our site I have an array that in the beginning contains all the clients of the company and as the script is run, some are removed. In the end, the remaining customers in the array must be updated with the INACTIVE Status on our site. The problem is that some records left in this array are returning this error message.

Follow the code snippet -

echo "Existem ".count($array_codigos) . " registros no banco SQL<br>";
                arsort($array_codigos);
                for($iy = 0; $iy <= count($array_codigos); $iy++){
                    $num++;
                    /******************************************************************
                     *   Deleta os clientes inexistentes do banco DBF do banco SQL    *
                     * Tabelas: Clientes, Contratos, Pagamentos, Boletos e Usuários   *
                     ******************************************************************/
                     $codigo_cliente = $array_codigos[$iy];
                     // TABELA CLIENTE
                    $consulta_cli = mysql_query("SELECT * FROM clientes WHERE cod_cliente = '$codigo_cliente'");

                    $num_cli = mysql_num_rows($consulta_cli);
                    if($num_cli != 0){
                        $array_cli = mysql_fetch_array($consulta_cli);
                        $status = $array_cli['status_cli'];
                        $nome_cliente = $array_cli['nome_cliente'];
                        if($status_cli != 'I'){
                            $update_inativo = mysql_query("UPDATE clientes SET status_cli = 'I' WHERE cod_cliente = $codigo_cliente");
                            if($update_inativo){
                                $inativos++;
                                echo "$iy - $codigo_cliente - $nome_cliente não existe no DBF - Atualizado para Inativo<br>";
                                $delete_users = mysql_query("DELETE FROM usuarios WHERE cod_cliente = $codigo_cliente");

                            }else{
                                $erro = mysql_error();
                                echo "$erro";
                            }
                        }
                    }
                }

The code is very long, if necessary, put other information.

Thank you in advance.

    
asked by anonymous 21.07.2016 / 22:30

1 answer

1

The index problem occurs ALWAYS that you are looking for an index in the array that does not exist.

Small examples:

In case of an array of numeric indexes:

<?php
$array = array('Ricdun', 'Markferum', 'Phiaan');
$indice = 3;

echo $array[ $indice ];

In this case it will result:

NOTICE Undefined offset: 3 on line number 4
  

Remember that array of this type always starts at zero, so the last element would be 2 .

In case of an array whose index is not numeric, such as:

$array = array('indice' => 'valor', 'nome' => 'Jenord', 'idade' => '12');

// Exibe nome:
echo $array[ 'nome' ]
// Ok! 

// Exibe pais:
echo $array[ 'pais' ]
// Erro!

This is because the index with the name pais does not exist, so the same error is returned.

Application in your case:

In your case, what can happen is this:

$array = array(
0 => 'Maria',
1 => 'Ana',
3 => 'João',
4 => 'Pedro',
7 => 'Lucas',
8 => 'Vitor',
9 => 'Luisa',
11 => 'Gustavo'
);

for($i = 0; $i <  count($array); $i++){
echo $array[$i];
echo '<br>';
}

Note that the index does not keep an exact order, for example, there is no index of number 2, 5, 6 and nor number 10, but I will get there.

  

Note: The lack of order in the index promotes two problems!

Maria
Ana

NOTICE Undefined offset: 2 on line number 13

João
Pedro

NOTICE Undefined offset: 5 on line number 13


NOTICE Undefined offset: 6 on line number 13

Lucas

Note that the PHP itself points out missing indexes. But note that it will not show the result of " Vitor ", " Luisa " and " Gustavo " and does not even point to error in index 10 .

This is because there are actually only 8 elements, but the last index is 11, higher than the number that will be obtained in count() . This way the loop is closed when $i < 8 , so it will end in 7 , stopping at " Lucas ".

Correction:

There are two easy ways to fix this.

1. Foreach :

Replace for() with foreach .

$array = array(0 => 'Maria', 1 => 'Ana', 3 => 'João', 4 => 'Pedro', 7 => 'Lucas', 8 => 'Vitor', 9 => 'Luisa', 11 => 'Gustavo');

foreach($array as $indice => $valor){

  echo '| Valor: '.$valor;
  echo '<br>';
  echo '| Indice: '.$indice;
  echo '<br><br>';

}

Result:

| Valor: Maria
| Indice: 0

| Valor: Ana
| Indice: 1

| Valor: João
| Indice: 3

| Valor: Pedro
| Indice: 4

| Valor: Lucas
| Indice: 7

| Valor: Vitor
| Indice: 8

| Valor: Luisa
| Indice: 9

| Valor: Gustavo
| Indice: 11

The difference, as you can see, is that foreach automatically ignores nonexistent indices. For foreach it does not matter which index is used.

Documentation: link

  

This method is recommended because indice stays the same!

2. array_values () + [loop] :

If the index does not matter and you do not need it, you can use array_values , so it will rewrite the array in a new array, having the correct order.

$array = array(0 => 'Maria', 1 => 'Ana', 3 => 'João', 4 => 'Pedro', 7 => 'Lucas', 8 => 'Vitor', 9 => 'Luisa', 11 => 'Gustavo');

$array = array_values ( $array );

for($indice = 0; $indice <  count($array); $indice++){

  echo '| Valor: '.$array[ $indice ];
  echo '<br>';
  echo '| Indice: '.$indice;
  echo '<br><br>';

}

Resulting:

| Valor: Maria
| Indice: 0

| Valor: Ana
| Indice: 1

| Valor: João
| Indice: 2

| Valor: Pedro
| Indice: 3

| Valor: Lucas
| Indice: 4

| Valor: Vitor
| Indice: 5

| Valor: Luisa
| Indice: 6

| Valor: Gustavo
| Indice: 7

Check that in this case the Indice is changed, so it keeps the order from 0 to 7. Therefore the old condition of $i < 8 fits correctly.

    
23.07.2016 / 07:38