Checking a value, using isset()

I have an array

Array
(
    [0] => Array
        (
            [building_id] => 1
            [name] => luke
            [number] => 44
            [notes] => 
        )

)

I’m tryin to display notes if any notes are present, but

foreach($buildingArray as $building) {
    if(isset($building['notes'])) {  
	  echo '<div class="alert alert-light shadow mb-5" role="alert"><h3 class="alert-heading">Notes</h3><hr>'.$building['notes'].'</div>';  
	  } 
}

returns…

<div class="alert alert-light shadow mb-5" role="alert"><h3 class="alert-heading">Notes</h3><hr></div>

If the array key exists in the array it will always be set to something, even it is set to null or an empty string.
Perhaps you would be better off looking for true/false values.
But I guess it depends upon your data source.
What is it actually set to when the data is absent?

should I do something like

if(isset($_POST['notes'])) { $notes = $_POST['notes']; } else { $notes = 0; }

then can I just use isempty() to test for 0?

So I assume the data source is a form. In that case $_POST['notes'] will always be set (assuming a text input).
In that case I would check for empty() or even empty(trim($_POST['notes']))
Rather than setting the value to 0 I would probably use null then you can check with if($notes), though checking twice seems redundant.

1 Like

To be safe you should be using something like

if (isset($_POST['notes'] && !empty($_POST['notes']) {
  $notes = $_POST['notes']
}
else {
  $notes = 0;
}

Checking isset && empty is redundant. Just empty will do. That won’t throw an E_NOTICE if the variable isn’t set.

I’d do it like this, that way you don’t need the else either.

$notes = 0;
if (!empty($_POST['notes'])) {
  $notes = $_POST['notes']
}

(I don’t like else)

2 Likes

You’re right. I had thought that way, but since it’s been a minute since I’ve done PHP, I thought I’d double check, and the comparison chart I had found was…not as clear as I obviously needed :shifty:

1 Like

Where this data is coming from and what you are using it for matters. This is why @SamA74 's replies contained conditional statements/questions. What you do changes depending on the context.

So, please answer the question of where this data is actually coming from and what are you doing with it? It appears to be coming from an sql query an you are producing a report (output) and you want to include specific html markup if there is a value in the ‘notes’ element?

Yes its coming f rom a form, I put it in a mysaql database and I wanmt to outpu tt only if it contains text

Then the simplest solution is to -

e.g.

if($building['notes']){
	echo '<div class="alert alert-light shadow mb-5" role="alert"><h3 class="alert-heading">Notes</h3><hr>'.$building['notes'].'</div>';
} 

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.