Array generates "Undefined offset" error

Asked

Viewed 16,952 times

1

Good afternoon I’m finalizing a script that will make some updates on our website I have an array that at 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 should be updated with the INACTIVE Status on our website. The problem is that some remaining records in this array are returning this error message.

Follows excerpt from the code -

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 quite extensive, if necessary, put other information.

Thank you in advance.

  • What would line 779 be? Deducing the error, the problem would be here: '$codigo_client = $array_codigos[$iy]'. If users, their array, is not sorted 0, 1, 2, 3.... This will occur.

  • 1

    In the second line of your code (here posted!), edit the arsort($array_codigos); for $array_codigos = array_values ($array_codigos). Check if the same problem persists.

1 answer

7

The index problem occurs WHENEVER you are searching for an input in the non-existent array.

Small examples:

In the case of an array of numerical indices:

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

echo $array[ $indice ];

Then it will work:

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 the case of an array whose Indice is not numerical, 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 there is no index with the name pais, so the same error will be 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 maintain an exact order, for example, there is no index number 2, 5, 6 and neither the 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 PHP itself points to the missing indices. However note that it will not display the result of "Vitor", "Luisa" and "Gustavo" and even points error in the 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(). That way the loop is closed when $i < 8, so it will end in 7, stopping at "Lucas".

Correction:

There are two easy ways to correct this situation.

1. Foreach:

Replace the for() for 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>';

}

Upshot:

| 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 the foreach automatically ignores the missing indices. For the foreach it does not matter what the input used.

Documentation: http://php.net/manual/en/control-structures.foreach.php

This method is recommended because the indice remains the same!

2. array_values () + [loop]:

If the index doesn’t matter and you don’t need it, you can use the array_values, this way it will rewrite the array in a new one, possessing 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 properly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.