I have this code:
if($coupon->excluding_discounted){
if(!$product->price_after_discount){
// do something
}
}
The code worked perfectly but I thought to convert this to one if ...
dd($coupon->excluding_discounted,!$product->price_after_discount);
1
false
How to check if the value of something is 1 and another element is false to do something ...?
Update:
my full code:
$products->map(function($product) use($coupon){
if($coupon->excluding_discounted && !$product->price_after_discount){
user()->cart()->updateExistingPivot($product, [
'coupon_id' => $coupon->id,
]);
}
});
the logic of code is if the product has discount and the excluding_discounted in coupon is true do the reset of code
I tried like this but it store the coupon_id even there is a discount on product! but with if inside if worked perfectly
You can join if statements together, like so:
if ($coupon->excluding_discounted && !$product->price_after_discount) {
// do something
}
If you want to test strictly the value of a variable you can use the === operator :
if (1 === $coupon->excluding_discounted
&& false === $product->price_after_discount
) {
// do something here
}
Related
I have a boolean field that is represented by 0 and 1 in my database.
if ($request->input('submitted')) {
// do code
}
This has been working because it's only been setting the field to 1 (true) but now there's a new flow that can revert the submission.
It has not been setting it back to 0 when I pass the value 0 in from the frontend and I assume it's because that condition is getting skipped since 0 would eval to null.
Is the best way to handle it:
if (isset($request->input('submitted'))) {
// do code
}
or would strictly checking against null work better:
if ($request->input('submitted') !== null) {
// do code
}
The simply approach parse your input to a boolean.
if ((bool) $request->input('submitted')) {
This will create the following results. Therefor removing your edge case.
(bool) "1" // true
(bool) "1" // false
An alternative approach is to use inbuilt PHP filter, it will parse a lot of cases more notably "true" and "false" to true and false.
if (filter_var($request->input('submitted'), FILTER_VALIDATE_BOOLEAN)) {
I would like to maintain a number of rules in a custom post type.
A rule will basically contain the expression part of an PHP IF construct, together with some output content.
In my plugin, I would like to loop through these rules, and for each rule use the rule in an IF expression, and then if true, do something with the associated output content.
I plan to store the rule expression as a text field, but how can I take this text field and use it in the IF expression?
I have tried to add the expression to a variable in PHP, and then use that variable as the expression. This doesnt seem to be working.
<?php
// Basic idea
// Wordpress query ($args not detailed in this example)
$rules = get_posts( $args );
// Example of post_meta field: tmbd_rule
// Post A -> tmbd_rule = '$varA == 2 && $varB > 17'
// Post B -> tmbd_rule = '$varA == 3 && $varB = 28'
foreach ($rules as $rule) {
$expression = $rule -> tmbd_rule;
if ($expression) {
// Do something clever
}
}
So - I am looking for this run through the list of rules and "do stuff" when a rule/condition is met :-)
You could use phps built-in eval() function in order to evaluate the result of your rules.
You can benefit from expression language it can be used without Symfony Framework as standalone library
https://symfony.com/doc/current/components/expression_language.html
For example(taken from docs):
class User
{
public $age;
}
$user = new User();
$user->age = 34;
$expressionLanguage->evaluate(
'user.age in 18..45',
[
'user' => $user,
]
); // true
I can see now two options for this, which is secure. One what #Robert proposed.
Second, you create 3 inputs, two select list and a text field.
1 select list will contain the variable name. ('variable')
1 select list will contain the operation. ('operation')
1 text field will contain the value which is desired. ('value')
Than you need to match and build 'together' the condition with ifs.
foreach ($rules as $rule) {
if ($rule->condition == '==' && $rule->variable == $rule->value || $rule->condition == '!=' && $rule->variable != $rule->value) {
// Do something clever
}
}
If you need more than one condition, than you need to group together and create a 4th field which says if it's or or and the connection between them. In this case the loop changes, like you check every condition separately, and than you looking for the second condition set (or/and) if it's fulfill your requirements according to your operation.
So what I wanna do is when a user pushes the submit button, a php query is run. In that php query if an "If statement" condition is fulfilled, I want to execute an operation (which in my case is a page redirection) and return false.
[EDIT] The whole query code is something like this:
add_filter( ‘mycred_add’, ‘mycred_pro_restrict_negative_balances’, 1, 3 );
function mycred_pro_restrict_negative_balances( $reply, $request, $mycred ) {
if ( $reply === false || $request[‘amount’] > 0 ) return $reply;
extract( $request );
// Users current balance
$current_balance = $mycred->get_users_balance( $user_id, $type );
// If balance is zero – decline OR If we are deducting points, make sure the amount will not take us below zero
if (( $current_balance <= 0 )||(($current_balance – abs( $amount )) < 0 )) {
$redirect_to_page = 22;
return false;
}
return $reply;
}
I wanna know if the query will work?? And if there's something wrong with it, please do mention the correction. Thanks in advance for helping / trying to help me.
In your calling function, test for a FALSE return value. If it's false, then call your redirection after processing any other actions you need to do upon this function returning FALSE.
You probably nead something like that:
if ( $current_balance <= 0 ) {
/* Redirection */
header("Location: http://www.example.com/page10.php");
exit();
}
Sending header 'Location' will tell browser to go to specified URL. That's the simplest way of redirection. You don't have to return false.
I have this id_role input that validates dependent on value of another input internet_access.
id_role's Validator Chain have one Callback validator that must check against empty/null values, others validators from this chain must check against filled values only.
I already made possible checking against empty/null values by $id_role->setContinueIfEmpty(true) but this applies to every validator in the chain. I need it to apply to only Callback validator of the chain.
This is the actual id_role input:
$id_role = new Input('id_role');
$id_role->setContinueIfEmpty(true); //this allows to check against empty/null values
$id_role->getFilterChain()
->attach($FilterInt);
$id_role->getValidatorChain()
->attach(new Validator\Callback(function($value, $context=array()){
return isset($context['internet_access']) && $context['internet_access'] == 1 && $value === 0 ? false : true;
}))
->attach(new Validator\Db\RecordExists(...);
So my problem is that Callback validator works fine but it fails on DbRecordExists because it tries to find a record that is empty. DbRecordExists must try to find a record only when id_role is actually filled.
Is there a way to do what i want in a elegant way (inside Input Filter and/or Input)?
The second parameter of ValidatorChain::attach method is $breakChainOnFailure, default value is false.
Check out docs at http://framework.zend.com/manual/2.2/en/modules/zend.validator.validator-chains.html
You should modify your code as:
$id_role->getValidatorChain()
->attach(
new Validator\Callback(
function($value, $context=array()){
return isset($context['internet_access']) && $context['internet_access'] == 1 && $value === 0 ? false : true;
}
),
true //$breakChainOnFailure
)
->attach(new Validator\Db\RecordExists(....));
Well i think there is no way of checking for empty/null values only in specific validators of the chain, because when i do $id_role->setContinueIfEmpty(true) it affects the whole Validator Chain, not just one specific validator, wich is the correct behavior.
So to accomplish what i needed, i had to put DbRecordExists Validator inside the Callback Validator and validate it manually only when values aren't empty/null:
$id_role = new Input('id_role');
$id_role->setContinueIfEmpty(true);
$id_role->getFilterChain()
->attach($FilterInt);
$id_role->getValidatorChain()
->attach(new Validator\Callback(function($value, $context=array()){
if (isset($context['internet_access']) && $context['internet_access'] == 1 && $value === 0) {
return false;
}
if ($value !== 0) {
$dbRecordExists = new Validator\Db\RecordExists(...);
if (!$dbRecordExists->isValid($value)) {
return false;
}
}
return true;
}));
I don't know if it is the best solution but well, it worked. I hope this can be of some help to others that have the same problem.
I have this if statement
if (!(#$donnees['mode']['delete'] === true || #$donnees['mode']['display'] === true)){
//doSomething only if mode is not delete nor display
}
i used # to not get the notice when mode is not set.
because if i use isset instead it would be even uglier :
$cond_delete = isset($donnees['mode']['delete']) && $donnees['mode']['delete'] === true;
$cond_display = isset($donnees['mode']['display ']) && $donnees['mode']['display '] === true;
if (!($cond_delete || $cond_display)){
//doSomething only if mode is not delete nor display
}
Is there a more concise way to do this ?
Thanks
If $donnees[ 'mode' ][ 'delete' ] / $donnees[ 'mode' ][ 'display' ] will only ever be A) set to true, or else B) set to false or something that would be considered false when converting to boolean -- e.g. undefined, NULL, 0, "0", empty string -- then you can omit the === true and just let them evaluate to true or false. E.g.:
if ( ! (
#$donnees[ 'mode' ][ 'delete' ] ||
#$donnees[ 'mode' ][ 'display' ]
) ) {
// doSomething only if mode is not delete nor display
}
// if
What other elements may $donnees[ 'mode' ] contain?
Unless you're just learning to program and don't know what you're doing yet, then notices (E_NOTICE) are just a nuisance and I'd disable them if possible. With notices disabled, if you want to know if an array element actually exists, then you can use array_key_exists() or isset(), depending exactly what you're trying to find out. If you just want to access the variable / array element and have it evaluate to NULL if it's undefined (which will evaluate to false when converting to boolean, as in an if / else expression), then you don't need to bloat your code with unnecessary tests that add no value.
Something like this might be a good choice although it creates a couple of single use variables.
/*Either set values if setting available, or set false*/
$cond_delete = isset($donnees['mode']['delete'])? $donnees['mode']['delete']: false;
$cond_display = isset($donnees['mode']['display '])? $donnees['mode']['display ']: false;
/*Where either mode is set do something*/
if (!($cond_delete || $cond_display)){
//doSomething only if mode is not delete nor display
}
if (isset($donnees['mode']['delete'], $donnees['mode']['display']) AND ($donnees['mode']['delete'] === true || $donnees['mode']['display'] === true)){
//doSomething only if mode is not delete nor display
}