简体   繁体   English

两种不同数据类型之间的php算术运算

[英]php arithmatic operations between two different data types

hi first of all I'm new to here. 嗨,首先,我是新来的。

i need all of your help 我需要你的全部帮助

below is my coding 下面是我的编码

<?php


 $a=1; 
 $b="hello";

$c=$a+$b."<br>"; 
$d=$b+$a."<br>";

 echo $c; 
 echo $d;
?>

output 产量

1 1个

1 1个

i need to know whats happening why answer is 1 in both ways is there any priority for data types in php 我需要知道发生了什么,为什么两种方式的答案都是1,所以php中的数据类型没有任何优先级

This scenario is otherwise called as Type-Juggling 这种情况下也称为Type-Juggling

The variable $b="hello"; 变量$b="hello"; will be cast to int (in this case it will be a 0) when you did the addition operator. 当您执行加法运算符时,将强制转换为int (在本例中为0)。 If the variable had $b="2hello"; 如果变量有$b="2hello"; , your output would have been 3 ,您的输出将为3

See this code. 请参阅此代码。

<?php
$foo = "0";  // $foo is string (ASCII 48)
$foo += 2;   // $foo is now an integer (2)
$foo = $foo + 1.3;  // $foo is now a float (3.3)
$foo = 5 + "10 Little Piggies"; // $foo is integer (15)
$foo = 5 + "10 Small Pigs";     // $foo is integer (15)
?>

PHP Manual

Your $a is an integer and $b is an string. $a是整数, $b是字符串。 When you add integer to string, string is converted to integer. 将整数添加到字符串时,字符串将转换为整数。 In your case $b = "hello" is converted to integer 0 . 在您的情况下, $b = "hello"转换为整数0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM