Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Need reliable way to check if element of multi-dim array exists?

Status
Not open for further replies.

BobMCT

IS-IT--Management
Sep 11, 2000
756
US
I've been searching and searching, trying and trying and I cannot get this to work accurately. Hopefully some of you PHP guru's can provide some advice?

I'm trying to increment the count of a two dimensional array element using the ++ operator. But if the element does not already exist the code throws and error. I know the error can be suppressed but that technique also suppresses all other errors as well. I first tried array_key_exists but that doesn't work on multi-dim arrays.
This error occurs with either incrementing or even just referencing in my code.

Here is the incrementing:

if (!isset($array["$key1"]["$key2])) { $array["$key1"]["$key2] = 0; }
$array["$key1"]["$key2]++;

and the output:

if (isset($array["$key1"]["$key2])) { print $array["$key1"]["$key2]; }

Hopefully someone who has run into this before can help?

Thank you . . . [ponder]
 
Code:
$array[$key1][$key2] = isset($array[$key1][$key2]) ? $array[$key1][$key2] + 1 : 0;

are you sure that the default should be to increment or set to zero? If this is handling counts, it would be more logical for it to increment or set to one.

if the latter is the case, then despite the illogicality and potentially poor cross-language practice of not instantiating variables, it is orders of magnitude quicker to suppress the errors. reports I have found show that the adding conditions suggests that the process across 300000 array elements increases execution time by 10000 times (still less than 0.1 microseconds however). I've not applied any analysis beyond reading the report; timing these things accurately in interpreted languages is never entirely straightforward.

Code:
@$array[$key1][$key2]++;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top