I know why I am getting this error, and this is because there currenly no ratings for this specific dish, so it is null or empty but I am not sure how to handle it.. I tried this but still the same error came up..
if(empty($rate_dishes[$j]["DishRating"]["dish_id"]))
{
echo $this->Form->hidden('dish_id', array('value'=> $this->params['var']));
}
else
{
echo $this->Form->hidden('dish_id', array('value'=> $rate_dishes[$j]["DishRating"]["dish_id"]));
}
Basically I am providing the dish id if its not provided by the posted array.. Whenever there is a rating for that particular dish it takes the 'else' condition.. but if it does not have a rating.. it gets to the first condition and still shows that error..
the URL would be /special_dishes/rate_dishes/4/?var=4
You probably shouldn't check for empty indices in that case, but rather if the array key exists. This is not really a feature of CakePHP, but rather just a standard PHP method.
The PHP function for this is isset() rather than empty(), as the latter expects the key to be there:
isset($rate_dishes[$j]["DishRating"]["dish_id"])
Also, there's array_key_exists(), but I believe you're looping through all the data in that post array, so using isset() is probably just fine.
Related
I inherited a Laravel project and I'm still working my way through learning it. I see in the code there is a check to run a block only if the $patient->records is there but check for it is:
if(! empty($patient->records) && $patient->records->count() > 0)
is that redundant or is empty and count() checking 2 separate things?
EDIT: corrected from > 1 to > 0
I think it's redundant. $patient->records is a collection.
I use like this.
if($patient->records->count())
{
// has records
}
If there is a possibility that $patient or records (assumed to be a property of $patient) can be undefined, then the empty($patient->records) is helpful because $patient->records->count() by itself would result in a fatal error:
Uncaught Error: Call to a member function count() on null in ...
With empty($patient->records) in the if clause, that fatal error can be avoided, even in the case that $patient or records is undefined.
The empty is checking that $patient->records is defined and not empty, while the count() part of the clause is a more specific check on the result of the count method. That method is not available in the case where $patient or records is undefined.
Yes, it is redundant.
Then, why someone can possible have written the code this way?
May be, before checking the length of the collection he wanted to make sure that it's not null though I prefer using is_null() or isset() method instead in such case. Even if that(null safe) was in his mind, still it's unnecessary. Because if the relationship between patient and records defined correctly(one to many => hasMany()) then $patient->records will always return a collection but never null. Even if it's an empty collection you can still use count() method safely without even checking if the records is null or not because it's never going to be null if we return a hasMany() relation.
What could be a better solution
You can just use this same condition removing the empty checking part as below:
if($patient->records->count() > 0)
To make it more readable, Laravel collection is offering us a very nice method called isNotEmpty():
if($patient->records->isNotEmpty())
This is what I prefer to use. Because we write code to make it readable to other programmer/us, not for computer. Computer can even understand binary but we don't write binary.
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.
$newOrders is an array and contains order objects...
order_id is an objects variable. I want to compare the order_id value to another variable($orderId) in If loop...
but it fails
Here is my code:
if($newOrders[$i]->order_id == $orderId){
echo "voila, found it:".$newOrders[$i]."<br>";
return $newOrders[$i];
}
Whenever I come across a piece of code that does not work - especially comparisons - I print out both sides of the variables (and often break down more complex variables, like your array) and actually look at the information, rather than assume I know from looking at the code.
It is inevitably a problem that is obvious as to what is wrong when the data is dumped out or otherwise manually examined. Tools such as Symfony VarDumper or just print_r, or an IDE with breakpoints and variable inspection are all suitable to see exactly what is going on.
Are you sure this array contains object, have you checked? If yes, then how ?
What is the variable $i there, could you please put full code (I believe snippet should be in some loop for or foreach)
You can always check for a valid object of a class by
if ($newOrders[$i] instanceof Order) { //Presuming Order is your class name
//do your stuff
}
You can also check by using var_dump() function to check the variables inside the object.
I hope it'll help.
I have code that is used very extensively which fetches an array from another method, and sometimes returns the first element of that array. Given that null is an acceptable return value for the function, is it worth the performance overhead of calling isset() on the array index (or checking the array length, etc), or is it better to just return the non-existant index (warnings aside). What are the advantages of calling isset() aside from preventing the warning.
The example below is simplified, the real function doesn't just get the first element of the array.
Return index which may not exist:
function get_array_element(){
$array = get_array(); // function that returns array
return $array[0]; // return index 0 which may not exist
}
Versus checking if index is set:
function get_array_element(){
$array = get_array(); // function that returns array
return (isset($array[0]))? // check if index 0 isset() else return null
$array[0] :
null;
}
Throwing a notice when accessing an undefined index -- in theory -- should alert you for typos in key names. In practice, if you’re using isset first, you probably just copied the key name there. Or used a numeric index. Or a constant.
On the other hand, in most cases you’re accessing an index withour caring wether it’s set or not -- and in this scenario, using isset is just anoying. A lot of languages lets you just retrieve any index without warnings, Javascript for example: just returning an undefined.
So I would advice to ignore the notice. Not all of them, because in some cases there really are helpful, so keep them turned on in development, but silence such array access by using #. Yes, it is ugly, but does its job:
return #$array[0];
Or in simple cases, maybe other solutions fit?
return array_shift($array);
Calling isset inside that function is semi-pointless because you are returning null if it doesn't exist, but null will be returned from $array[0] regardless of whether you use isset of not.
If it only throws an E_NOTICE then I wouldn't worry about it, just check for get_array_element() == null.
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;