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.

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Great, thanks. Logic is not my strongpoint. Adding Ors into the mix doesn't help!
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';}

4 Comments

Cheers. Only accepted the other answer as there was more explanation, but I'm using your script…
That gives me the error: "Fatal error: Cannot use isset() on the result of an expression (you can use "null !== expression" instead)"
it should not happen both codes are working. Before I corrected an error maybe you have the older version.... try again....
As suspected the issues were with my code. $_POST['area'] actually matches $code, not $area.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.