/    Sign up×
Community /Pin to ProfileBookmark

Most efficient php array management

I am populating an array with values I read in from the database.

At the same time, I generate an array of unique values e.g. `$deptList[$row[“dept”]]++`

Now, this generates a PHP Notice: `PHP Notice: Undefined index: DeptB` on the first loop of each new dept.

Is it more efficient to leave this and hide PHP Notices than it is creating an if statement to handle?

I don’t like errors but, is adding an extra if statement really needed?

Which is more efficient:

Now
`$deptList[$row[“dept”]]++` – Generates an Undefined index error on the first occurence only – then it is fine

After
`isset($deptList[$row[“dept”]])?$deptList[$row[“dept”]]++:$deptList[$row[“dept”]]=0` – Adds an extra if statement to every single loop and removes PHP Notice.

to post a comment
PHP

1 Comments(s)

Copy linkTweet thisAlerts:
@NogDogDec 13.2021 — First question: do you really need this, or could it be solved by count() when you actually need it? (I.e., is there some sub-array of things in $deptList[$some_key_or_whatever] that would already give you that total by getting a count() of it?)

If you just want to accept the warning condition, you can suppress it just for that command with the @ operator:
[code=php]
@$deptList[$row["dept"]]++;
[/code]

If you want to make sure your code is forward compatible on the off chance they ever make that an error instead of a warning, you could create a little function for whenever you need it:
[code=php]
function increment(&$foo) { // note "&" to pass argument by reference
$foo = is_null($foo) ? 1 : ++$foo; // need to use the "prefix" version of ++
}

// usage:
increment($deptList[$row["dept"]]);
echo $deptList[$row["dept"]]; // 1
[/code]
×

Success!

Help @php-bgrader spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.7,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...