1

I am in a bind, multiple times on a page for different form items, I insert a css div class into a form item ONLY if an error_array key exists, this is how I highlight a form item that has an error in it.

Works, great if I have an error because then my error array is set, problem is before an error is set, it tries to look for an array key that does not exist. I was thinking using php's isset function first would be the ticket but I guess you cannot combine isset with another function?


<?php
//this works
$search_array = array('first' => 1, 'second' => 4);

if (array_key_exists('first', $search_array)){
    echo "good";
}


// this does not work, will give write errors
$search_array = array('first' => 1, 'second' => 4);

if (isset(array_key_exists('first', $search_array))){
    echo "good";
}

// Here is  1 example how I need to make the end result work
$country_class = (array_key_exists('country', $signup_errors)) ? ' signup_error' : ' signup_good';
echo '<select name="country" id="country" class="textarealong ' .$country_class. '"/>';
?>

In other parts I use it like this

<?PHP echo(array_key_exists('password', $signup_errors)) ? ' signup_error' : ' signup_good';?>

And I need to have it be a 1 line code if possible

3 Answers 3

4

If isset is false, the second statement wont get executed, because the parsers knows that both statements have to be true to get the whole statement true.

   $country_class = ( isset($signup_errors) && array_key_exists('country', $signup_errors)) ? ' signup_error' : ' signup_good';

BUT i would suggest you to initialize every variable you are using...

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

2 Comments

Also about your comment, doesn't this initialize this variable?
No it wont because even if array_key_exists auto-vivifies $signup_errors (and I'm pretty sure it doesn't), then the failure of isset() will cause it not to run at all. isset() obviously is not allowed to vivify the variables it tests.
0

I'm not familiar enough with PHP syntax, but this sounds like a job for short-circuit evaluation, i.e. || or &&, where the second term is not evaluated if the first term alone can determine the result (if it's True in || or False in &&).

Comments

0

This is an old question, but it's an even simpler answer. isset checks the array and the key. This works great and doesn't generate any notices if the array is not set:

if (isset($search_array['first'])){
    echo "good";
}

Or:

$country_class = isset($signup_errors['country']) ? ' signup_error' : ' signup_good';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.