0

I have simple PHP code like this

$revenue = $this->dailyCounts['revenue'][$date]['net_revenue'] + (!empty($activity[$date]) ? $activity[$date] : 0) * 1000;

But here it is always showing warnings when the $activity variable is NULL even though I am checking for empty. I am running this inside a loop and it is always showing undefined index when $activity has null value.

Niranjan N Raju
  • 12,047
  • 4
  • 22
  • 41
Happy Coder
  • 4,255
  • 13
  • 75
  • 152

3 Answers3

1

Using isset instead of empty won't solve any problem in that case.

No warning is generated if the variable does not exist. That means empty() is essentially the concise equivalent to !isset($var) || $var == false.

http://php.net/manual/en/function.empty.php

I guess the notice comes from $this->dailyCounts['revenue'][$date]['net_revenue']

  • No it is not. When I added the isset() check , it has gone. I am using this in Laravel 5 – Happy Coder Oct 27 '15 at 08:26
  • @HappyCoder: can you paste your fixed code? This shows that both do not produce warnings and give the same results: http://codepad.org/HjgrZ3RZ – HectorJ Oct 27 '15 at 08:39
0

use isset() instead of empty(),

(!isset($activity[$date])

empty() will directly check the value, but isset() will see if the index is there or not.

See this and this for more information, its explained nicely.

Community
  • 1
  • 1
Niranjan N Raju
  • 12,047
  • 4
  • 22
  • 41
0

Try this :

$revenue = $this->dailyCounts['revenue'][$date]['net_revenue'] + ((isset($activity[$date]) && !empty($activity[$date])) ? $activity[$date] : 0) * 1000;
Piotr Olaszewski
  • 6,017
  • 5
  • 38
  • 65