0

I have an array say $packages. I have the code like this to prevent the undefined variable error.

$hospital_charge=0;
    if(!empty($packages)){
    foreach($packages as $package){
        $hospital_charge=$package['hospital_charge'];

Then in subsequent code I use

$health_card_discount = ((($a*5)/100)+($hospital_charge*.05));

That is if $hospital_charge have a null value, I get the error undefined variable hospital_charge,

so to prevent that I defined $hospital_charge=0

is this the proper way of doing it or there is better way of achieving this?

Note:I am using PHP 5.4.16

1
  • Yes It's valid , you can also use isset(). Commented Apr 29, 2015 at 18:58

1 Answer 1

1

You can always use isset (it will check that the variable is defined and not null:

$health_card_discount = isset($hospital_charge) ? ((($a*5)/100)+($hospital_charge*.05)) : (($a*5)/100);

But the way you are doing it is also valid.

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

2 Comments

Thanks taxicala - Assuming that you want to check both $a and $hospital_charge with isset how you can achieve that?
Same way, use a ternary comparison but i recomend moving the code to a function with an if statement.

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.