PHP comparison operation and logical operation _php Example

Source: Internet
Author: User
Tags logical operators scalar

1. The following values are judged to be true with empty ():

Unassigned variables, undeclared variables, 0, "0", "", false, NULL, empty array array (), magic Method of Objects __get () value returned by

In versions below PHP5.0, objects that do not have any properties are also judged by empty to be true

Note: empty () only accepts index or property values for variables or variables, cannot pass directly to constants, and cannot pass in an operational expression, which supports expressions after PHP 5.5

2. Values judged to be false by Isset (): Unassigned variables, undeclared variables, NULL, __get () returned values, accepted participation empty (), cannot be constants and expressions.

3, different types of data comparison

If one is Boolean or null, convert to a Boolean comparison,

Otherwise, if there is a number, converted to number comparison,

Otherwise, if there is a string, convert to string comparison

Object type is always greater than array type and scalar type, array type is always greater than scalar type

Note the results of these comparisons:

The numeric string at the beginning of 0 is not converted by octal, but simply discards the ' 0 ' discard by number comparison,

  123== ' 0123 '//true ' 123 '
  < ' 0124 '//true, The numeric string at the beginning of 0 is compared directly to the decimal number instead of

  the octal "012" =//False
=//true
  0x12 = =//True
  "0x12" =//True
 

 FA LSE < TRUE; True
 2>true;//False
 2==true;//True 
 null==0;//true
-1<0;//true
-1<null;// False,-1 turn bool is true

4. Type conversion rules

was empty () the value that evaluates to true is converted to Boolean to get false, conversely, to get True (__get () return value to be judged by the specific value)

the value evaluated by empty () to be true is converted to number 0, and the non-empty array number gets 1 (the value returned by __get () is judged by the specific value)

Class test{
 private $k =1;
 Public Function __get ($propertyName) {return
  123
 }}

$obj = new Test ();
echo Json_encode (Empty ($obj->k)); True
Echo Json_encode (isset ($obj->k));//false
Echo Json_encode ((bool) ($obj->k));//true

A few strings to the number of the scene:

Echo ' abc ' *1; 0 
Echo ' 012 ' *1//12 multiplication: Can convert hexadecimal number, not the beginning of the number return 0
echo ' 0x12.123 ' *1;//18

Echo (float) ' 0x12 ';//0 
echo (int) ' 0x12 '; 0 cannot process hexadecimal number
echo (float) ' 12abc ';//12 intercepts the left string
echo (float) ' abc ';//0 is not a number return 0

is_numeric (' 0x123 '); True to recognize the hexadecimal number
is_numeric (' 0x123.123 ');//false identify the target as an entire string instead of intercepting the previous part

String to the left of the numeric string to be converted, if not to return 0.

Other data-transfer strings:

The value of several spin strings (string) 0; "0"
(string) true;//"1"
(string) false;//"
(string) null; ""
(String) array (); "Array"

Arrays can be string concatenation directly but not mathematically.

Object type conversion to Boolean is always true, object types cannot be converted to number and string, and therefore cannot be string concatenation and mathematical operations

A scalar is converted to an array by setting the first element of the array to a scalar and returning the array.

A scalar is converted to object to obtain an instance of a StdClass class, and a scalar value is assigned to an attribute named Scalar: object ([scalar] => 234)

Array object to get an instance of the StdClass class, the array key for the strength of the property name.

Object-array is a bit complicated:

Methods, static properties, class constants are discarded

Protection property name is preceded by a "*"

The private property is prefixed with the class name (the case is exactly the same as that of the class)

These prefixes are preceded by a null character.

For example, an array that is converted by object is:

Array ([*v] => 444 [BF] => 333 [BK] => 99977 [Ak] => 999 [*p] => 888 [A2] => 22)

The original objects are:

Public property A2, protected Properties V, p, which class cannot be distinguished from (overridden to take the attributes of a subclass)

From class B's Private property F, K, (from the array key to the BF, for example, can not determine whether he is the property name of the Bf, or from the Class B private property F)

Private property K from class A

Cannot identify B and a which is a subclass which is a parent class (only from the array key and cannot infer which class the original object is constructed from)

Example:

Class A {
 private $A = ' private property, $A of Class A ';//This'll become ' \0a\0a '
 protected $C = ' protected P Roperty, $C of Class A ';
}

Class B extends A {
 private $A = ' private property, $A of Class B ';//This'll become ' \0b\0a ' public
 $AA = ' Pub Lic property, $AA of Class B '; This is become ' AA '
 protected $B = ' protected property, $B of Class B ';
}

$arr = (array) new B ();

foreach ($arr as $key => $value) {
 echo ' <br/> ';
 echo $key. ', Length: '. strlen ($key). ' Value: '. $value;
}

Output results:

Ba,length:4 Value:private Property, $A the Class B
aa,length:2 Value:public property, $AA of Class B
*b,length: 4 value:protected property, $B of Class B
aa,length:4 value:private Property, $A of Class A
*c,length:4 value : Protected property, $C of Class A

5, the logical operation always returns TRUE or false (note to the people who write more JavaScript), logical operator precedence from high to low for &&, | |, and, or, short-circuit effects of logical operators can be used in statements, but remember they don't look like JAVASCR In IPT, returns a value that is not a Boolean and is used in an expression to be aware of.

$a = 1;
$b =0;
$b and $a =;
echo $a; 1
$b | | $a =;
echo $a; 200

6, switch comparison is not "= = =" but "= =" (in JavaScript is "= = =")

7. In PhP4, the comparison between object is the same as array, in php5, the "= =" Comparison between object types is true if they belong to an instance of the same class (and, of course, the comparison of attributes, which is similar to the scalar "= =" comparison), Obje The comparison of "= =" between ct is true if they are the same object.

In PHP4, an object that does not include any member variable is judged by empty () to be true

String offset empty () Decision: Take the character of offset to judge, before PHP5.4, the index is rounded before using the index to take characters from the string, so the string with no digits on the left is converted to 0. After PHP5.4, the string index for the non-shape format is no longer rounded, so the judgment is true, and the Isset () is judged to be false. Such as:

$str = ' ab0d ';
Empty ($str [0]); False
Empty ($str [0.5]);//false index is rounded down to 0
empty ($str ["0.5"]); the//false index is rounded down to 0,php5.4 and is not forensics after the decision is true 
Empty ($str [2]); True, the character obtained is "0"
Empty ($str ["3"])//false, the character obtained is "D"
Empty ($str [4]),//true, the index is out of range, notice warning, but empty () Ignores warning
empty ($str [' a ']);//False, the left does not contain a numeric string index PHP5.4 before being processed as $STR [0],php5.4] directly to the decision true

Whether it's "not equal to" or "= =", do not use "transitivity" in the cross-type data comparison of PHP:

$a = = $b; True

$b = = $c; True

does not indicate $a = = $c is True

Comparison method of arrays

Arrays are
function Standard_array_compare ($op 1, $op 2) that are compared using the standard comparison operators
{
 if (count ($op 1) < count ($op 2)) {
  return-1//$OP 1 < $op 2
 } ElseIf (Count ($op 1) > Count ($op 2)) {return
  1;//$OP 1 > $op 2
 }
 foreach ($op 1 as $key => $val) {
  if (!array_key_exists ($key, $op 2)) {return
   null;//Uncomparable
  } elseif ($val < $op 2[$key]) {
   return -1;
  } ElseIf ($val > $op 2[$key]) {return
   1;
  }
 }
 return 0; $op 1 = $op 2
}

8, ternary operator: Unlike most other programming languages, PHP ternary operators are left-bound!

$arg = ' T '; 
 $vehicle = ($arg = = ' B ')? ' Bus ': 
     ($arg = = ' A ')? ' Airplane ': 
     ($arg = = ' T ')? ' Train ': 
     ($arg = = ' C ')? ' Car ': 
     ($arg = = ' H ')? ' Horse ': 
     ' feet '); 
 Echo $vehicle; Horse

The three-dimensional operational expressions are divided into

($arg = = ' B ')? ' Bus ': ($arg = = ' A ') 
         ? ' Airplane ': ($arg = = ' T ') 
                ? ' Train ': ($arg = = ' C ')
                    ? ' Car ': ($arg = = ' H ')
                         ? ' Horse ': ' feet ';

The comparison of the above PHP operation and logic calculation is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.