0

Maybe it's just a different PHP.INI setting (this is happening on a shared hosting after an automatic update) but the essential two lines of code:

$k = array();
// some code ...
$k["assoc"]++;

If you ask why I am doing it, it's just the fastest way I know to count which and how many "elements" I have when I can only read them one at a time from "somewhere".
No problem with PHP 5, but PHP 7 is telling me this:

Notice: Undefined index: assoc in *******

I do not know in advance what associative indexes I can have, so I cannot set them at zero beforehand.

So the question is: what is the proper way to initialize an associative array in PHP7, and maybe since I am asking, is there a way to force all the elements to be e.g. integers and be set at zero by default?

ZioBit
  • 905
  • 10
  • 29
  • 2
    Your assumptions about PHP 5 are incorrect ~ https://3v4l.org/AbAoY. You must have just had your `error_reporting` set too low (or off entirely) – Phil Oct 28 '20 at 04:12
  • 1
    Why not put in a check to see if the array already has the key in question before using `++`? `if (array_key_exists("assoc", $k)) $k["assoc"]++; else $k["assoc"] = 1;` [Repl.it](https://repl.it/@esqew/VirtualParallelUnits#main.php) – esqew Oct 28 '20 at 04:14
  • ... or use something simple like `$k["assoc"] = ($k["assoc"] ?? 0) + 1;` – Phil Oct 28 '20 at 04:15
  • @Phil Thanks for the shorthand version! Been a while since I worked with PHP every day and safe to say that was not a convention I was exposed to frequently. – esqew Oct 28 '20 at 04:16
  • @esqew I only get exposed to it on StackOverflow these days. It's been about 10 years for me. Stack keeps me fresh – Phil Oct 28 '20 at 04:17

0 Answers0