Reputation: 2208
Each time I am getting some information from database I am repeating the isset checking or if the variable is true. Is there any smart way to make it in a different way?
If I will not do this and the variable is empty it gives me an error so I can't really go over it.
I believe that I am doing something not necessary and it makes code longer.
$variable = DB::select('SELECT * FROM `table_name`');
$variable2 = DB::select('SELECT * FROM `table_name2`');
if (isset($variable)){
if ($variable == 1){
doSomething();
}
}
if ($variable2){
if ($variable2 == 1){
doSomething2();
}
}
EDIT: I just realized that if an empty variable did not give me any errors it would be processed through all the next functions without any sense and it would make it much more complicated to find the places where the entire script was faulty.
Well, it probably means that my problem is actually an advantage haha.
Upvotes: 0
Views: 91
Reputation: 87719
If you do something like this:
Route::get('/select', ['as' => 'debug.select', function () {
// select
$var = DB::select('select * from users where email = 1');
// convert to boolean
dd(!!$var);
}]);
You'll see that the result is:
false
While
Route::get('/select', ['as' => 'debug.select', function () {
// Select 1 user
$var = DB::select('select * from users limit 1');
// Convert an array to boolean / empty arrays === false on PHP
dd(!!$var);
}]);
Is
true
That being said, using your code
$variable = DB::select('SELECT * FROM `table_name`');
$variable2 = DB::select('SELECT * FROM `table_name2`');
if (! $variable) {
doSomethingWhenNothingWasFound();
}
if ($variable) {
doSomethingIfFound();
}
if ($variable2) {
doSomething2();
}
Upvotes: 1