1

Using the following code, I'm getting the error "Undefined Index: area"

<select id="area" name="area" class="selectbox dropdownfilter" data-target-id="location">
    <option value="">all areas</option>
    <?php asort($areas) ?>
    <?php foreach ($areas as $code =>$area) : ?>
    <option value="<?php echo $code ?>"<?php if(isset($_SESSION['area']) | isset($_POST['area'])) { if($_SESSION['area'] == $area | $_POST['area'] == $area) { echo ' selected'; } } ?> ><?php echo $area ?></option>
    <?php endforeach ?>
</select>

It's outputting the $area correctly, the error is coming in the 'selected' script. Bit lost as to what I'm doing wrong, or how else I could do it. I'm just trying to select the option if it's what was submitted in the search form.

Albzi
  • 15,431
  • 6
  • 46
  • 63
Badger
  • 467
  • 4
  • 17
  • possible duplicate of [PHP: "Notice: Undefined variable" and "Notice: Undefined index"](http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-and-notice-undefined-index) – Rizier123 Feb 26 '15 at 11:31

2 Answers2

1

The error "Undefined Index: area" means that $_POST['area'] or $_SESSION['area'] is indeed set.... but the other one is not...

use this:

if((isset($_SESSION['area']) && $_SESSION['area'] == $area) || (isset($_POST['area']) && $_POST['area'] == $area)) {echo ' selected';}

or like this:

 if(@$_SESSION['area'] == $area || @$_POST['area'] == $area) {echo ' selected';}
Federico
  • 1,231
  • 9
  • 13
  • Cheers. Only accepted the other answer as there was more explanation, but I'm using your script… – Badger Feb 26 '15 at 11:46
  • That gives me the error: "Fatal error: Cannot use isset() on the result of an expression (you can use "null !== expression" instead)" – Badger Feb 26 '15 at 12:01
  • it should not happen both codes are working. Before I corrected an error maybe you have the older version.... try again.... – Federico Feb 26 '15 at 12:08
  • As suspected the issues were with my code. $_POST['area'] actually matches $code, not $area. – Badger Feb 26 '15 at 12:31
1

That condition:

if(isset($_SESSION['area']) | isset($_POST['area'])) {

=> Returns true if $_SESSION['area'] is set OR $_POST['area'] is set
So it is true if $_SESSION['area'] is not set but $_POST['area'] is set, for example.

Then :

    if($_SESSION['area'] == $area | $_POST['area'] == $area) {

=> You are testing $_SESSION['area'] value. If it's not set (it's possible as seen before), you'll have an error notice.

Here is what I'd do, only one condition :

if (
    (isset($_SESSION['area']) && $_SESSION['area'] == $area)
    ||
    (isset($_POST['area']) && $_POST['area'] == $area)
) {

If $_SESSION['area'] is not set, PHP won't bother to test if $_SESSION['area'] == $area because it doesn't need to (as the 1st condition is false anyway), it will try what is after the OR

See http://php.net/manual/en/language.operators.logical.php
And http://php.net/manual/en/language.operators.precedence.php