Avoid multiple PHP Notice: Undefined index: within a for loop

-1

The variable $words concatenates the result of a query in a column of a table where the words are comma-separated.

Only when running the script for each word inside the for is generated a PHP Notice: Undefined index: agua in ....

If there are 50 words will be generated 50 PHP Notice: Undefined index: PALAVRA_DO_FOR in ...

$palavras = explode(',', $words);
$ocorrencias = array();

for($i = 0; $i<count($palavras); $i++){
   $palavra = $palavras[$i];
   $ocorrencias[$palavra]++;
}

How to avoid these PHP Notice: Undefined index: ... ?

PHP Version 5.4.43

    
asked by anonymous 13.07.2017 / 20:22

3 answers

3

The error occurs because PHP attempts to access an array key that may not initially exist. For example, in the first word, $ocorrencias is an empty list and when you do $ocorrencias[$palavra] you are accessing a nonexistent key. To get around the error, just check if the key exists and, if it does not exist, create it with a value of zero.

<?php

$words = "stack,overflow,em,portugûes";
$palavras = explode(',', $words);
$ocorrencias = array();

for($i = 0; $i < count($palavras); $i++){

    $palavra = $palavras[$i];

    // Se a chave não existir, crie-a com valor zero:
    if (!isset($ocorrencias[$palavra])) {
        $ocorrencias[$palavra] = 0;
    }

    $ocorrencias[$palavra]++;

}

print_r($ocorrencias);
  

See working at Ideone .

    
13.07.2017 / 20:40
2

One way to solve this problem is to initialize the occurrence array with all elements already zeroed, with the function #

Then you can change array_fill_keys() to for and only increment the key.

$words = 'teste,abc,2015,teste,13,abc,2015';

$palavras = explode(',', $words);
$ocorrencias = array_fill_keys($palavras, 0);

foreach($palavras as $item){
    $ocorrencias[$item]++;
}

Return:

Array
(
    [teste] => 2
    [abc] => 2
    [2015] => 2
    [13] => 1
)
    
13.07.2017 / 20:39
-3

I might very well suggest you to disable PHP warning messages in your script this way:

ini_set('display_errors', FALSE);

But it would not be very convenient, because the most appropriate is to work your script to contain a clean code, because it is better to correct the error than to hide it. To do this, simply use a PHP function ( isset ) to check if the index exists before attempting to use it.

Example:

$palavras = explode(',', $words);
$ocorrencias = array();

for($i = 0; $i<count($palavras); $i++){
  if (isset($palavras[$i])) {
    $palavra = $palavras[$i];
    $ocorrencias[$palavra]++;
  }
}
    
13.07.2017 / 20:54