Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for loop with isset() != null - why?

Tags:

php

for($i=0; isset($_POST['key_str'][$i]) != null; $i++)
{
    // some php here
}

I've inherited some legacy code at work and I've found above for() loop in several places. I've been writing PHP, Javascript and Python for years now and have never seen anything like this. My gut tells me this is the person who wrote this legacy code came from a different language. And may have not been very experienced.

Questions:

1) Does isset($_POST['key_str'][$i]) perform better than count($_POST['key_str'])?

2) Does this resemble syntax that you'd typically find in another language? If so, which language?

like image 594
b_dubb Avatar asked Feb 03 '26 15:02

b_dubb


1 Answers

Inside isset, $i (which is incremented in the loop) is used in this expression. $_POST['key_str'][$i], which is part of the check.

So basically, $_POST['key_str'] is expected to be an array, and this loop will loop over all items in that array.

If you like, you could use count(), or replace the whole thing with a foreach loop, although that may result in a warning if $_POST['key_str'] is not set at all or is not an array. isset is a very easy way to get around that, because it handles all those situations and will return false, so the loop will simply not be entered in that scenario.

like image 130
GolezTrol Avatar answered Feb 06 '26 05:02

GolezTrol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!