Php:undefined variable derived from array - php

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

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.

Related

Getting Undefined variable: type in laravel

I am getting this message
While trying to load a page. And its indicating to this line of code
return view('admin/vehicle-categories/index',compact('categories','level','parent_categories','type','parent_id'));
}
How can I solve this?
This was a breaking change introduced in PHP 7.2. Previously you could compact a named variable that was not yet defined. After 7.2 you must define the variable previous to adding to the compact method.
Broke a lot of code for us as well.
The fix is to simply define the variable before the compact statement, even if null. Be careful if going through a branch/if-check that you define it for certain:
$type == null // or value

Array check undefined offset php

I'll try to explain it.
i have a array:
$arrayTime = array(0=>"07",1=>"09", 3=>"13", 4=>"15", 5=>"17", 6=>"19");
Here you can see that is not defined offset 2
and now i need for my array and on offset 2 push number 0(for example)
I tried use this:
if($arrayTime[$i]==""){
$arrayTime[$i]=0;
}
Yes it works but 50 to 50 array looks like this:
$arrayTime = array(0=>"07",1=>"09", 3=>"13", 4=>"15", 5=>"17", 6=>"19",2=>"0");
but on the line where is the if it throws an error:
Notice: Undefined offset: 2 in C:\wamp\www\xxx.php on line 10
So i need same result, but without error.
Thanks for your help all :)
First of all, it doesn't throw an error. It gives you a warning about a possible bug in your code.
if($arrayTime[$i]==""){}
This attempts to access $arrayTime[$i] to retrieve a value to compare against your empty string.
The attempt to read and use a non-existing array index to get a value for comparison is the reason why it throws the warning as this is usually unexpected. When the key does not exist null is used instead and the code continues executing.
if(null == ""){} // this evaluates to true.
Because you are comparing against an empty string "", your answer would be empty():
if(empty($arrayTime[$i])){}
It means you are expecting a key not to exist and at the same time you are checking the value for emptyness. See the type comparison table to see what is and what is not considered 'empty'.
The same rules apply to isset() and is_null(), it wont throw the notice if the key does not exist. So choose the function that best serves your needs.
Keep in mind that by using any of these functions you are checking the value and not if the key exists in the array. You can use array_key_exists() for that.
if(array_key_exists($i, $arrayTime)){}
to add zeroes to your non-defined indexes without getting a Notice you should evaluate if the desired index to compare exists, so instead of comparing directly try checking the existence of the index first by using isset method, checking if the variable is defined and isn't NULL.
So your code to validate should look like this:
//check for the index before tryin' to acces it
if( !isset($arrayTime[$i]) ){
$arrayTime[$i]=0;
}
Hope it works for you.

php ternary shorthand for use in template

I'm building my first application with Kohana, and using a basic templating system within that. In my templates I want to echo variables for the various contents of the page, but only if each variable is set, and I want to keep the code in the templates as short as possible, so something like this:
<?=$foo?>
works fine if the variable is set, but if it's not I get a notice. So I thought a ternary operator would do the trick nicely:
<?=$foo?:''?>
according to the PHP manual, from 5.3 it's ok to leave out the middle part and the above should output nothing if the variable isn't set, but I still get an error notice."Notice: Undefined variable: foo in /"
I can get the desired result with a slight alteration to suppress the notice:
<?=#$foo?:''?>
but I know that's generally not beset practice and would like a better solution if possible, while still keeping the code to a minimum in the template files.
the following works, but it's not as concise (mainly because my actual variables can be quite long):
<?=isset($foo)?$foo:'';?>
am I missing something or doing something wrong?
The ternary operation is not meant to replace checking with isset() - it needs it's variable defined or else you get a notice.
Template engines usually offer a way to use a default value instead, but they also do not use pure PHP code. You you are out of luck here: Either suppress the notice, or use the longer code variant. Or ensure that every variable is set, which enables you to consider any notice an error.
To avoid notices for undefined variables, you can create custom function that takes first parameter by reference
function tplvar(&$value, $default = '') {
return ($value !== null) ? $value : $default;
}
<?=tplvar($foo, 'bar');?>
Uninitialized variables passed by reference will be seen as nulls.

Find Element in PHP Array (if exists)

I'm wondering if there is a more elegant way to do this:
$foo = (isset($bar) and array_key_exists('meh', $bar)) ? $bar['meh'] : '';
If I remove the isset part, PHP issues a warning if $bar isn't an array, if I remove the array_key_exists part, PHP issues a warning if the meh key isn't in the array. Is there a more graceful, warning free, way of achieving the same end?
You take exactly the steps required to "secure" code against the warnings you mention.
However, the warnings are there for a reason. Typically it makes more sense to check, if you can prevent situations where the variables you are trying to access are not initialized.
You can reference the key directly. Inside isset it won't even throw an exception if $bar is undefined.
$foo = isset($bar['meh']) ? $bar['meh'] : '';
The difference between array_key_exists and isset is that isset will return FALSE if the key corresponds to a NULL value. In my code above, a NULL value will therefore result in $foo begin the empty string, not NULL. If that is a problem your current approach will be the best.

PHP is it OK to try access an associative array if you are unsure the key exists?

Is it OK to rely on PHP's behaviour if a key is not in the array? Which is:
Attempting to access an array key which has not been defined is the same as accessing any other undefined variable: an E_NOTICE-level error message will be issued, and the result will be NULL.
For instance if I do not know $_POST contains certain keys is it OK to just try? I want the result to be null anyway. Or is there a better way?
Since you should always develop with error reporting turned on, you want to avoid triggering avoidable errors so as to keep error reporting useful to you. As such, no, it's not okay. Use isset or empty. For a more in-depth excursion into this topic see The Definitive Guide To PHP's isset And empty.
You can use isset() to check if it exists and if so do stuff.
if(isset($_POST["key"])){// do stuff}
You should use isset() or empty() to test it.
If it is necessary to check if a key exists even if it the key is set to null then array_key_exists(mixed $key , array $search) will be usefull. But it is very slow compared to isset(). So isset() shall be used if you check for a key that is in the array and not null.
isset()function can save you from the warning of index not found by checking for it first
isset($_POST['notSure']) ? $var= $_POST['notSure'] : $var = null;

Categories