rynhe
rynhe

Reputation: 2529

Adding string with number in php

$a = "3dollars";
$b = 20;
echo $a += $b;
print($a += $b);

Result:

23
43

I have a question from this calculation.$a is a string and $b is number.I am adding both and print using echo its print 23 and print using print return 43.How is it

Upvotes: 20

Views: 63637

Answers (6)

user15043253
user15043253

Reputation:

If you need both the values, return them in an array

Upvotes: 0

JC editx
JC editx

Reputation: 31

PHP automatically associates a data type to the variable, depending on its value. Since the data types are not set in a strict sense, you can do things like adding a string to an integer without causing an error.

In PHP 7, type declarations were added. This gives us an option to specify the expected data type when declaring a function, and by adding the strict declaration, it will throw a "Fatal Error" if the data type mismatches.

To specify strict we need to set declare(strict_types=1);. This must be on the very first line of the PHP file. Then it will show fatal error and if you didn't declare this strict then it convert string into integer.

Upvotes: 3

fyquah95
fyquah95

Reputation: 828

The right way to add (which is technically concatenating) strings is

$a = 7;
$b = "3 dollars";
print ($a . $b);  // 73 dollars

The + operator in php automatically converts string into numbers, which explains why your code carried out arimethic instead of concatenation

Upvotes: 5

arun singh
arun singh

Reputation: 31

PHP treats '3dollars' as a integer 3 because string starting with integer and participating in arithmetic operation, so

    $a = "3dollars";
    $b = 20;
    echo $a += $b;
    it echo 23;   //$a=$a+$b;

    now $a = 23 + 20;
    print($a += $b);    //$a=$a+$b;
    it print 43;

Upvotes: 0

ExploreTech
ExploreTech

Reputation: 21

Since You have created a variable for the two, it stores the result of each, so when you added $a to 20 it will echo 23 which stores in the system, them when you print $a which is now 23 in addition to $b which is 20. You will get 43.

Upvotes: -1

Ayush
Ayush

Reputation: 42450

It casts '3dollars' as a number, getting $a = 3.

When you echo, you add 20, to $a, so it prints 23 and $a = 23.

Then, when you print, you again add 20, so now $a = 43.

Upvotes: 21

Related Questions