Carania
Carania

Reputation: 1

if this echo this - if variable not there echo nothing

I have added a script to my website which shows a message when the product filter does not show up any results. The code I've included is this:

<?php
if(empty($htmlFilter->rows)){
  echo '<p>Sorry, no results found - try a different search selection</p>';
}
?>

This works, but the problem I'm having is that the message also shows up on the pages where the filter is not existent. I need to write a condition for when the filter does not exists on the page.

Can anyone help please?

Quick update: When I add var_dump($htmlFilter) it come sup with NULL

Is the variable not right?

Upvotes: 0

Views: 108

Answers (5)

Kid Diamond
Kid Diamond

Reputation: 2301

Normally you would expect an undefined variable error, but it silently just evaluates to true even though the variable is not set, which is a bad thing because not everyone is aware of this.

As a workaround you can additionally check if the variable is set before checking if its value is empty.

if (isset($htmlFilter) && empty($htmlFilter->rows)) {
    echo '<p>Sorry, no results found - try a different search selection</p>';
}

Upvotes: 2

Carania
Carania

Reputation: 1

I've finally fixed this - I used the following code:

if(empty($this->rows) && !empty($htmlFilter)){
echo '<p>Sorry, no results found - try a different search selection</p>'

It was also not put in the correct line :-/

All sorted now though - thanks for your help guys! :-)

Upvotes: 0

Tom&#225;s Cot
Tom&#225;s Cot

Reputation: 1013

You could use the isset function like this if I got what you wrote right.

<?php
if(empty($htmlFilter->rows) && isset($htmlFilter)){
  echo '<p>Sorry, no results found - try a different search selection</p>';
}
?>

EDIT:

This code:

<?php
echo is_null($algo);
echo '<br>';
echo isset($algo);
echo '<br>';
echo empty($algo);
?>

returns this:

1

1

As you can see, the variable $algo is not initialized nor declared.

Upvotes: 0

Anthony Garcia-Labiad
Anthony Garcia-Labiad

Reputation: 3721

If $htmlFilter->rows is supposed to be an array, you can do this:

<?php
if(isset($htmlFilter->rows) && count($htmlFilter->rows) === 0){
  echo '<p>Sorry, no results found - try a different search selection</p>';
}
?>

Upvotes: 0

Dipak G.
Dipak G.

Reputation: 725

Could you try...

<?php
if( isset($htmlFilter->rows) && empty($htmlFilter->rows) ) {
  echo '<p>Sorry, no results found - try a different search selection</p>';
}
?>

Upvotes: 0

Related Questions