For logical and faster purposes, whenever you make PHP try two statements using an AND condition, if the first one fails he doesn't attempt to try the second one... for logical and faster purposes that is beautiful indeed, but on my case I would need to know if the second statement also didn't work, so I don't need to make an user go through the same page a lot of times because the mistake was different than before...
So, assuming I have this:
if ($firstModel->validate() && $secondModel->validate()) {$sayCheese;}
How do I make it try both?
I did consider separating the models but I just want to know if there's an alternative.
Edit:
My form has multiple inserts for different models at the same time so the validation works beautifully if for a single model only, and since I need to try two or more at the same time, NOT stopping at the first statement is a MUST.
if ($firstTry & $thenTry) {$sayCheese;}
This will do a bitwise and, and check $thenTry even if $firstTry is false.
Edit : note I am just naively replying to your question, but I am not entirely sure why you would realistically want to do this.
You should consider to split the checks and your if-condition
$firstTry = checkOne();
$thenTry = checkTwo();
if ($firstTry && $thenTry) {
echo $sayCheese;
} else {
echo "check 1: ".($firstTry ? 'ok' : 'bad')."<br>";
echo "check 2: ".($firstTry ? 'ok' : 'bad')."<br>";
}
Related
I only have one case in switch statement
switch ($coreName) {
case 'stock':
$result['website'] = ($result['website']) ? $websiteStatus[$result['website']] : "";
break;
}
My question is this a good practice or shall I use an if statement for this? Any performance differences or anything?
Use if else Only when :
1. you have only 2 or more conditions OR You have multiple conditions in single if else.
And use switch when
1. You have to compare `ONE` variable value against multiple.
In your case if else is better
Nothing speaks against this from a technical point of view.
So the question to answer is: why did you implement a switch statement instead of an if conditional?
I'd say the default should be an "normal" if condition, unless special reasons point to a switch instead. The two primary reasons might be:
extensibility (for later additions)
readability (for other coders)
Especially the first case should be considered here. If it might become necessary to extend the handling, then certainly using a switch right away is a good practice.
If you go to phpBench.com and scroll down to see the results between if and case, you can see that using an if statement is slightly faster, but the results aren't too different. (Screenshot below)
You may as well use an if as it is easier to read, less code and is still faster (even by only a tiny amount).
if($corename === "stock") {
$result['website'] = ($result['website']) ? $websiteStatus[$result['website']] : "";
}
case should only be used when you compare multiple values rather than just one. This is the same as using elseif. Using if is the most suited for this specifically.
Why not simply do a simple if, like this :
if($coreName == 'stock')
{
$result['website'] = ($result['website']) ? $websiteStatus[$result['website']] : "";
}
Hope this helps.
So I am utilizing codeigniter.
To allow reusability of code i have a number of functions in my model which get different things.
e.g get_details, get_features, get_products
I then have a function called get_all which calls all these methods, so If i want i can get them all but otherwise i can use them individually.
So I have my data, and I pass it to my view. My view loops through each establishment and displays various data in a table row.
At present I use if.. else statements to discern if a value is empty for example.
So if an establishment has not had its features added yet I use:
if(!empty($features['feature1'])){//DO STUFF e.g output 'YES'}
Anyway, my views code is no getting rather long and complicated because essentially for each and every key of each array returned using get_all I am using an if..else statement to output a "-" if it is not set.
It works, it just seems repetitive.
The work around I thought of is to simply set a default array whereby everything is by default set to "-", then if the data does exist it is overwritten, but then I just have to write/initiate a large default array..
So my question is not a life threatening one, nor is it particularly hard.. I am simply curious as to how one achieves such functionality without ugly code.
Cheers
Maybe you can "adjust" the array in the controller, by setting its empty values to -:
$features = array_map(function($value) {
return empty($value) ? '-' : $value;
}, $features);
without you posting your actual code i can only provide some general advice. To usually handle this, and consolidate your code to remove all the conditionals put the keys in an array.
$keys_to_check = array('feature1', 'feature2', 'etc.....');
foreach ($keys_to_check as $key) {
if (!empty($features[$key])) {
// do something
}
}
This refactors out all those conditional statements into somethign that is more maintainable.
also in your model code when you are providing a general function get_all that calls 3 subfunctions it is extremely important to make sure that unecessary queries aren't being executed. it seems it would be good software design to not repeat yourself, and group 3 functions into 1 but if those three functions are each executing similar queries then it is horrible for performance.
Ok, first of all, i suspect this is going to be closed.
Right, i have a question relating to using function calls inside statements as opposed to assigning to a variable first.
For example:
(code is in php, but question applies generally. Also, code is overly simplified)
if (myAmazingFunction() === true) {
// do something amazing
}
instead of
$amazingresult = myAmazingFuncton();
if ($amazingResult === true) {
// do something amazing
}
The question is:
Is there any performance, or other underlying pros or cons to each approach
Stylistically, is any of the approaches considered better than the other
In most languages, there will be no performance difference. In the first case, the compiler will allocate storage for the result of the function call before checking whether it is true. In the second case you're simply making this explicit.
If you are debugging, sometimes the second form is easier, as you can set a breakpoint on the second line and check the value returned by the function before the comparison is made - but then you see the result of the function by the path the executing code takes anyway in the example you've given. You can also re-use the value without rerunning the function, as Zac says in his comment.
Stylistically, this is going to be largely subjective. The only thing I'd say here is that if your variable name makes the purpose of the function output clear, then you might be adding something to the ability for others to understand your code easily.
#DavidM's answer is correct. However, I'd just like to add that stylistically, I think it depends on the name of the function and its context.
Example:
if ($food->tastesGood()) {
echo 'Mmmm!';
}
// vs.
$foodTastesGood = $food->tastesGood();
if ($foodTastesGood) {
echo 'Mmmm!';
}
In this case, it's very clear that the return value of the method tastesGood() is going to be a boolean from both the name of the method and its context. Using a temporary variable adds nothing to your code except making it redundant and less-readable at a glance. In addition, if the variable is not defined right before its used, then you have to go find the definition to understand the condition. In these cases, I would say use of a variable is worse.
Another example:
if ($dishes->wash() !== FALSE) {
echo 'Sparkly!';
}
// vs.
$dishesAreClean = $dishes->wash() !== FALSE;
if ($dishesAreClean) {
echo 'Sparkly!';
}
In this case, we can't really infer the return type of the wash() method from its name, and indeed, it would seem that it returns nothing on success and FALSE on errors. Checking if the dishes are clean then requires us to make sure that there were no errors, but the first case doesn't make for particularly readable or self-documenting code. The second case, however, adds very explicit information about what's going on by way of the temporary variable. In these cases, I would say use of a variable is better.
Is there any performance, or other underlying pros or cons to each approach
Performance-wise, assigning an extra variable that you will use only in your if condition will use extra memory, and one useless line of code. So it will use more memory. Will it be noticeable? Probably not.
Stylistically, is any of the approaches considered bad
Using the method in your if statement is perfectly valid, and I think it's a better approach, since you can read the code and see exactly what value is being tested in the if condition. No need to look for the variable and search where it was affected.
As you all probably know, do loops execute at least once, even if the statement is false — while the while loop would never execute even once if the statement is false.
When are do loops useful? Could someone give me a real life example?
They're basically useful when you want something to happen at least once, and maybe more.
The first example that comes to mind is generating a unique ID (non sequentially) in a database. The approach I sometimes take is:
lock table
do {
id = generate random id
} while(id exists)
insert into db with the generated id
unlock table
Basically it will keep generating ids until one doesn't exist (note: potentially an infinite loop, which I might guard against depending on the situation).
The Do loop is very powerfull if you have to check multiple files etc. Due to the guarentee of iteration it will work all the way through.
do {
if($integer > 0) { $nameoffile[0]++; }
else { $nameoffile[0] = $nameoffile[0].$integer; }
$integer++;
} while(file_exists("directory/".$nameoffile[0].".".$nameoffile[1]));
Next to what has already been answered, you can do crude stuff like this with a do:
do
{
if ($cond1) break;
if ($cond2) continue;
do_something();
} while(true/false);
Which is a modification of a switch loop, which allows continue. You can simulate goto similarities in case goto is not available and similar.
It must not make your code more readable, so it's often not suggested to do that. But it technically works.
$specify_step = ($_GET['specify_step']) ? $_GET['specify_step'] : getNextStep($returnId,$type);
Given the above statement, is there a way to shorthand this if statement even more so that I don't have to say $_GET['specify_step'] twice?
In the cases when I'm accessing GET or COOKIES etc, it always seems redundant and "wordier" then it needs to be.
I don't think it gets much more compact than that. My only thought is to make a temporary variable to hold $_GET['specify_step'], but that doesn't seem any shorter.
$specify_step = ($_GET['specify_step']) ?: getNextStep($returnId,$type);
It made enough logical sense to me that I had to go look it up....and according to php.net, it works in PHP 5.3. If you're using 5.3, you're in luck.
As I mentioned in a comment to your question, I don't know PHP.
Check if this works. In most langauages, if the first part is true, the function getNextStep won't be called.
$specify_step = ($_GET['specify_step']) || getNextStep($returnId,$type);
There would be this alternate boolean evaluation approach, but it just goes to show that you have to duplicate something:
$specify_step = $_GET['specify_step']
or
$specify_step = getNextStep($returnId,$type);
(Also works without decorative linebreaks.)
With PHP 5.3 you might of course use the ?: shortcut. If that's available.
Personally I can alternate to $_GET->default('specify_step', 123) for such cases.