Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Notice: Undefined index when trying to increment an associative array in PHP

Tags:

arrays

php

I'm trying to increment the value for $variable each time a duplicate variable occurs. I'm not sure if this is syntactically correct, but I think this is semantically correct. var_dump seems to spit out the correct outputs, but i get this error: Notice: Undefined index...

$newarray = array();
foreach ($array as $variable)
{
    $newarray[$variable]++; 
    var_dump($newarray);
}

$array = (0 => h, 1 => e, 2 => l, 3=> l, 4=> o);

goal:

'h' => int 1
'e' => int 1
'l' => int 2
'o' => int 1

My code works, it's just that I get some weird NOTICE.

like image 753
diesel Avatar asked Nov 09 '11 08:11

diesel


People also ask

How do I fix PHP Notice Undefined index?

Undefined Index in PHP is a Notice generated by the language. The simplest way to ignore such a notice is to ask PHP to stop generating such notices. You can either add a small line of code at the top of the PHP page or edit the field error_reporting in the php. ini file.

How do you declare an associative array in PHP?

You can also just create an array by simply stating var[array_key'] = some_value' . Save this answer.

Are PHP arrays associative or integer indexed?

There are two kinds of arrays in PHP: indexed and associative. The keys of an indexed array are integers, beginning at 0. Indexed arrays are used when you identify things by their position. Associative arrays have strings as keys and behave more like two-column tables.

What does Undefined index mean in PHP?

When using them, you might encounter an error called “Notice: Undefined Index”. This error means that within your code, there is a variable or constant that has no value assigned to it.


2 Answers

$newarray = array();
foreach ($array as $variable)
{
    if (!isset($newarray[$variable])) {
        $newarray[$variable] = 0;
    }
    $newarray[$variable]++;
}
like image 142
Your Common Sense Avatar answered Sep 28 '22 08:09

Your Common Sense


Take a look at the function array_count_values(). It does exactly what you are trying to do.

Sample from php.net:

$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));

Result:

Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)
like image 31
codaddict Avatar answered Sep 28 '22 07:09

codaddict