Home Backend Development PHP Tutorial Learn comparison operations and logical operations in PHP through examples

Learn comparison operations and logical operations in PHP through examples

Jul 25, 2016 am 09:07 AM

  1. class Test{

  2. private $k=1;
  3. public function __get($propertyName){
  4. return 123;
  5. }
  6. }

  7. < p>$obj = new Test();
  8. echo json_encode(empty($obj->k)); //true
  9. echo json_encode(isset($obj->k)); //false
  10. echo json_encode( (bool)($obj->k)); //true
  11. ?>

Copy code

string When converting number, intercept the numeric string on the left for conversion, if not then returns 0,

  1. //A few converted string values

  2. (string)0 ; // "0"

  3. (string)true ; // "1"
  4. (string)false; // ""
  5. (string)null; // ""
  6. (string)array(); // "Array"
  7. ?>

Copy code

Arrays can directly perform string concatenation operations but cannot perform mathematical operations. It is always true to convert the object type to boolean. The object type cannot be converted to number and string, so string concatenation and mathematical operations cannot be performed. The way to convert a scalar to an array is to set the first element of the array to a scalar and return the array. The scalar is converted to object to get an instance of the stdClass class, and the scalar value is assigned to the property named scalar: Object( [scalar] => 234) Convert array to object to get an instance of stdClass class. The key of the array is the attribute name of the class. Converting object to array is a bit complicated: Methods, static properties, and class constants are discarded Protected attribute names are preceded by a "*" Private properties are preceded by the class name (the case is exactly the same as the class name)

For example, an array converted from object is: Array( [*v] => 444 [bf] => 333 [bk] => 99977 [Ak] => 999 [*p] => 888 [a2] => 22)

The original objects include: public attribute a2, protected attributes v, p, which class these attributes come from cannot be identified (if overridden, the attributes of the subclass will be taken) Private attributes f and k from class b (from the perspective of the array key, taking bf as an example, it is impossible to determine whether the attribute name is bf or the private attribute f from class b) private property k from class A It is impossible to identify which of b and A is the subclass and which is the parent class (just from the key of the array, it is also impossible to infer which class the original object was constructed from)

5. Logical operations always return true or false (people who write a lot of JavaScript should pay attention). The priority of logical operators from high to low is &&, ||, and, or. The short-circuit effect of logical operators can be used in statements. , but remember that they will not return a value that is not a boolean type like in JavaScript, so be careful when using it in expressions.

  1. $a = 1;
  2. $b=0;
  3. $b and $a = 100;
  4. echo $a; //1
  5. $b || $a = 200;
  6. eacho $a; //200
  7. ?>
Copy code

6. The comparison of switch is not "===" but "==" (in javascript it is "===")

7. In php4, the comparison method between objects is the same as that of array. In php5, the "==" comparison between object types is true only if they belong to instances of the same class (of course, attributes must also be compared Comparison, this is similar to the "===" comparison of scalars), the "===" comparison between objects is true only if they are the same object.

In PHP4, objects that do not include any member variables are judged to be true by empty()

String offset offset takes the character's empty() judgment: Take the character corresponding to offset for judgment. Before PHP5.4, when using the index to get characters from the string, the index will be rounded first, so the left side does not contain Numeric strings are converted to 0. After PHP5.4, string indexes in non-integer formats are no longer rounded, so it is judged to be true. Similarly, isset() is judged to be false. For example:

  1. $str = 'ab0d';
  2. empty($str[0]); //false
  3. empty($str[0.5]); //false The index is rounded down is 0
  4. empty($str["0.5"]); //false The index is rounded down to 0. After PHP5.4, no evidence is obtained and it is determined to be true
  5. empty($str[2]); //true , The obtained character is "0"
  6. empty($str["3"]); //false, the obtained character is "d"
  7. empty($str[4]); //true, the index is out of range, notice warning , but empty() will ignore the warning
  8. empty($str['a']); // false, the left side does not contain a numeric string index before PHP5.4 and is processed as $str[0], after PHP5.4, Directly copy the code to determine true
  9. ?>

Whether it is "not equal to" or "==", do not use "transitiveness" in cross-type data comparison in PHP: $a == $b; //true $b == $c; //true It does not mean that $a == $c is true

Array comparison method

  1. //Arrays are compared using standard comparison operators
  2. function standard_array_compare($op1, $op2)
  3. {
  4. if (count($op1) < count($op2) ) {
  5. return -1; // $op1 < $op2
  6. } elseif (count($op1) > count($op2)) {
  7. return 1; // $op1 > $op2
  8. }
  9. foreach ( $op1 as $key => $val) {
  10. if (!array_key_exists($key, $op2)) {
  11. return null; // uncomparable
  12. } elseif ($val < $op2[$key]) {
  13. return -1;
  14. } elseif ($val > $op2[$key]) {
  15. return 1;
  16. }
  17. }
  18. return 0; // $op1 == $op2
  19. }
  20. ?>
Copy Code

8. Ternary operator?:, unlike most other programming languages, PHP's ternary operator is left associative!

  1. $arg = 'T';
  2. $vehicle = ( ( $arg == 'B' ) ? 'bus' :
  3. ( $arg == 'A' ) ? 'airplane ' :
  4. ( $arg == 'T' ) ? 'train' :
  5. ( $arg == 'C' ) ? 'car' :
  6. ( $arg == 'H' ) ? 'horse' :
  7. 'feet ' );
  8. echo $vehicle; //horse
  9. ?>
Copy code

The ternary operation expression is divided into ( $arg == 'B' ) ? 'bus' : ( $arg == 'A' ) ? 'airplane' : ( $arg == 'T' ) ? 'train' : ( $arg == 'C' ) ? 'car' : ( $arg == 'H' ) ? 'horse' : 'feet' ;



Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles