iBrazilian2
iBrazilian2

Reputation: 2293

How to add two variables together in PHP?

I'm currently trying to put two variables together, one that has already a specific number automatically calculated by imagesy and the second variable is returning data from url with $_GET['l2_y']

imagettfstroketext($jpg_image, 0, $y . $options['text']['font-position']['l2_y'] );

The $y returns '29'

and the $options['text']['font-position']['l2_y'] returns +150 (or whatever I set in the header)

I am trying to combine the two but it's not working at all, if I remove the $y . then the +150 works but if I add the . it doesn't calculate everything..

I've been stuck at this for a while now, I'm not sure how to combine the two, the reason I am using + signs in get is because it can also be used as a -150 to change the position of the text.

Upvotes: 1

Views: 31574

Answers (4)

Mohammad Alabed
Mohammad Alabed

Reputation: 809

Here you go:

<?php
    $var1 = '1';
    $var2 = '+1';
    $var3 = '-1';
    
    echo $var1 + $var2; //2
    echo $var1 + $var3; //0
?>

Upvotes: 2

somethinghere
somethinghere

Reputation: 17340

You could try to coerce both numbers to integers using intval and then add them (using + and not ., which is used for concatenating strings):

intval($y) + intval($options['text']['font-position']['l2_y'])

That way you are sure both are numbers before you add them (so you avoid any unwanted results).

However, it is not necessary to coerce them into integers if you simply use the + (adding) operator and not the . concatenation operator, as the following works as well:

echo '+2' + 3; // outputs 5

PHP automatically coerces numbers, intval is useful if you want to be sure it is a number (usually when somebody inputs a number into your site).

Upvotes: 7

jDo
jDo

Reputation: 4010

I think this is what you're after:

imagettfstroketext($jpg_image, 0, intval($y) + intval($options['text']['font-position']['l2_y']));

. is for strings, + is for numbers. In case $y and/or $options['text']['font-position']['l2_y'] are strings (which they are if they have quotes around them), cast them to integers with intval(). PHP will interpret +150 as 150 and -150 as -150

Upvotes: 1

Alfie Goodacre
Alfie Goodacre

Reputation: 2793

You shouldn't be using the . operator, this will concatenate the values as if they were strings. The correct way to do this would require the use of +.

For example: imagettfstroketext($jpg_image, 0, $y + $options['text']['font-position']['l2_y'] ); assuming that $y is a number and not a string.

Using the values you have, this will return the number 179, whereas the version using the . operator will return a string which contains the value "29150"

If the values are not numbers and are in fact strings, you can also encapsulate each variable in an intval($var) which will take the integer value of the variable if it exists.

Upvotes: 1

Related Questions