Expressions in PHP

What is Expression?

  • The term “expression” in programming refers to a combination of symbols and elements that, when evaluated, produce a value.

Arithmetic Expression

  • Arithmetic expressions involve mathematical operations and can include addition, subtraction, multiplication, division, modulus, and exponentiation.

Arithmetic Expressions

  • $a = 10;
  • $b = 5;
  • $sum = $a + $b;
  • $difference = $a – $b;
  • $product = $a * $b;
  • $quotient = $a / $b;

“People hate on PHP because it’s cool to hate on PHP and most of those most likely haven’t written a line of PHP”

Do you know?

There was no formal specification/standard for php till 2014.

String Expression

String expressions manipulate and concatenate strings, which are sequences of characters.

  • $firstName = “John”;
  • $lastName = “Doe”;
  • $fullName = $firstName . ” ” . $lastName;

Comparison Expressions

Comparison expressions evaluate to boolean values based on comparisons between variables or values.

  • $x = 10;
  • $y = 5;
  • $isGreater = ($x > $y);

What is an expression in programming?

  • A) A comment explaining the purpose of a code block.
  • B) A sequence of statements that perform a specific task.
  • C) A combination of values, variables, operators, and/or function calls that can be evaluated to produce a value.
  • D) A loop that repeats a block of code a certain number of times.
  • C) An expression is a combination of values, variables, operators, and/or function calls that can be evaluated to produce a value. It represents a computation or a data manipulation task.

Logical Expressions

  • $isTrue = true;
  • $isFalse = false;
  • $logicalAnd = ($isTrue && $isFalse);
  • $logicalOr = ($isTrue || $isFalse);

Ternary Expression

  • The ternary operator (? 🙂 is a concise way to write simple conditional expressions. It has the form condition? true_expression : false_expression. It’s a powerful tool for assigning values based on a condition.

Ternary Conditional Expression

  • $age = 18;
  • $isAdult = ($age >= 18) ? “Yes” : “No”;

Array Expressions

  • $numbers = array(1, 2, 3, 4, 5);
  • $sumArray = array_sum($numbers);
  • $countArray = count($numbers);

Precedence and Grouping

  • $result = 2 * (3 + 4); // This ensures addition is done before multiplication

[pdf_note link=”https://drive.google.com/file/d/1Fv-DpOrZ4tPb_z7fdfO7mKBxg9vPlyEj/view”]