Spex3
    

PHP: Booleans, Arrays, Objects, Null, and Constants


    

    

PHP: Booleans, Arrays, Objects, Null, and Constants

1. Booleans
A Boolean in PHP represents true (1) or false (0). Booleans are often used in conditional statements.

✅ Example:

 
<?php
$isPHPFun = true;
$isJavaHard = false;

var_dump($isPHPFun); // Output: bool(true)
var_dump($isJavaHard); // Output: bool(false)
?>



✅ Booleans in Conditions:




<?php
$loggedIn = true;

if ($loggedIn) {
echo "Welcome, User!";
} else {
echo "Please log in.";
}
?>



2. Arrays
An array is a collection of values stored under a single variable. PHP supports three types:

Indexed Arrays (Numeric keys)

Associative Arrays (Named keys)

Multidimensional Arrays (Arrays inside arrays)

🔹 Indexed Arrays (Numeric Keys)

<?php
$fruits = ["Apple", "Banana", "Cherry"];
echo $fruits[0]; // Output: Apple
?>


🔹 Associative Arrays (Key-Value Pairs)

<?php
$person = ["name" => "John", "age" => 30];
echo $person["name"]; // Output: John
?>


🔹 Multidimensional Arrays


<?php
$students = [
["John", 25, "A"],
["Alice", 22, "B"],
];

echo $students[0][0]; // Output: John
?>


3. Objects
An object is an instance of a class. Objects allow data to be stored as properties and methods.

✅ Example:



<?php
class Car {
public $brand;

function setBrand($brand) {
$this->brand = $brand;
}
}

$myCar = new Car();
$myCar->setBrand("Toyota");
echo $myCar->brand; // Output: Toyota
?>


4. NULL in PHP
NULL is a special data type that represents a variable with no value.

A variable is NULL if it:

Has not been assigned a value.

Has been set to NULL.

Has been unset().

✅ Example:




<?php
$var = NULL;
var_dump($var); // Output: NULL
?>



5. PHP Constants
A constant is a value that cannot be changed during script execution.

Defined using define() or const.

✅ Using define() (Works in PHP 5.3+)




<?php
define("SITE_NAME", "MyWebsite");
echo SITE_NAME; // Output: MyWebsite
?>



✅ Using const (Works in PHP 5.6+)



<?php
const PI = 3.14159;
echo PI; // Output: 3.14159
?>



✅ Case Sensitivity

By default, constants are case-sensitive.

Use true as the third parameter in define() to make them case-insensitive.



<?php
define("GREETING", "Hello, World!", true);
echo greeting; // Output: Hello, World!
?>



Conclusion
Booleans are useful for logic (true or false).

Arrays store multiple values (indexed, associative, multidimensional).

Objects represent real-world entities with properties and methods.

NULL represents a variable with no value.

Constants store values that never change during execution.


    Date: 2025-03-28 00:00:00.000000