Asked  7 Months ago    Answers:  5   Viewed   64 times

I have a string variable, $operation, that can have values like + or - and two integer variables $initial and $unit.

So to echo the result of the arithmetic operation between them

I have to use something like

 if($operation == '+') echo ($initial + $unit);
 if($operation == '-') echo ($initial - $unit);

Is there a way I can do this without the IF?

 Answers

97

trickery with math:

echo $initial + (($operation == '-') ? -1 : 1) * $unit;

only using addition, but cheating with multiplying by a negative... :)

Saturday, May 29, 2021
 
hillz
answered 7 Months ago
20

You need to use raw expression like that :

$products =  DB::table('products')
        ->join('hasDiscount', 'products.idProd', '=', 'hasDiscount.idProd')
        ->join('discounts', 'discounts.idDiscount', '=', 'hasDiscount.idDiscount')
        ->select(DB::raw('products.*,(products.price * discounts.tauxDiscount/100) as newPrice'))
        ->get();

https://laravel.com/docs/5.4/queries#raw-expressions

Wednesday, March 31, 2021
 
supermitch
answered 9 Months ago
60

This is happening because the concatenation operator has a higher precedence than the addition or subtraction operators, but multiplication and division have a higher precedence then concatenation.

So, what you're really executing is this:

echo ("$a + $b  = " . $a) + $b;
echo ("$a - $b  = " . $a) - $b;

In the first case, that gets turned into this:

"1 + 2 = 1" + $b

Which PHP tries to convert "1 + 2 = 1" into a number (because of type juggling) and gets 1, turning the expression into:

1 + 2

Which is why you get 3. The same logic can be applied to the subtraction condition.

Instead, if you put parenthesis around the calculations, you'll get the desired output.

echo "$a + $b  = " . ($a + $b);
echo "$a - $b  = " . ($a - $b);
Saturday, May 29, 2021
 
JohnnyW
answered 7 Months ago
54
list( $name, $book, $from, $to ) = preg_split( '/[ :-]/', 'Luke 1:26-38' );

echo $name; //"Luke"

    /* Split results in an Array
(
    [0] => Luke
    [1] => 1
    [2] => 26
    [3] => 38
)
     */
Saturday, May 29, 2021
 
jsuggs
answered 7 Months ago
69

A quick fix may be:

$string = '15 hours 6 minutes 2 seconds';
$pattern ='/ d+ w+$/';
$string = preg_replace($pattern, ' and$0', $string);

However, you may want to look into a nicer solution which resulted in the following array being built:

$time = array($a, $b, $c, $e, $q);

You could then do:

$time = array_filter($time);
$last = array_pop($time);
$string = implode(', ', $time) . ' and ' . $last;
Saturday, May 29, 2021
 
Webroots
answered 7 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share