Arrays and Objects
Arrays and objects are PHP's fundamental data structures for organizing and managing complex data. Arrays let you store multiple values in a single variable, while objects allow you to create custom data types with both properties and behaviors.
What You'll Learn
- How to create and use indexed arrays
- Working with associative arrays (key-value pairs)
- Multidimensional arrays
- Common array functions
- Creating and using objects
- Object properties and methods
- Practical applications of arrays and objects
Indexed Arrays
Indexed arrays use numeric indices starting from 0:
<?php
// Creating an indexed array
$fruits = ["Apple", "Banana", "Orange", "Mango"];
// Accessing elements
echo "First fruit: " . $fruits[0] . "\n";
echo "Second fruit: " . $fruits[1] . "\n";
// Array with array() syntax (older style)
$numbers = array(10, 20, 30, 40, 50);
echo "Third number: " . $numbers[2] . "\n";
// Adding elements
$fruits[] = "Grape"; // Adds to the end
echo "New fruit: " . $fruits[4] . "\n";
// Array length
echo "Total fruits: " . count($fruits) . "\n";
Associative Arrays
Associative arrays use named keys instead of numeric indices:
<?php
// Creating an associative array
$person = [
"name" => "Alice",
"age" => 25,
"city" => "New York",
"occupation" => "Developer"
];
// Accessing elements
echo "Name: " . $person["name"] . "\n";
echo "Age: " . $person["age"] . "\n";
echo "City: " . $person["city"] . "\n";
// Adding new elements
$person["email"] = "alice@example.com";
echo "Email: " . $person["email"] . "\n";
// Modifying elements
$person["age"] = 26;
echo "Updated age: " . $person["age"] . "\n";
// Checking if key exists
if (isset($person["occupation"])) {
echo "Occupation: " . $person["occupation"] . "\n";
}
Iterating Over Arrays
Use loops to process array elements:
<?php
$colors = ["Red", "Green", "Blue", "Yellow"];
// Using foreach for indexed arrays
echo "Colors:\n";
foreach ($colors as $color) {
echo "- $color\n";
}
echo "\n";
// Using foreach with index
foreach ($colors as $index => $color) {
echo ($index + 1) . ". $color\n";
}
echo "\n";
// Associative array iteration
$product = [
"name" => "Laptop",
"price" => 999.99,
"brand" => "TechCorp",
"in_stock" => true
];
echo "Product Information:\n";
foreach ($product as $key => $value) {
echo "$key: $value\n";
}
Multidimensional Arrays
Arrays can contain other arrays, creating multiple dimensions:
<?php
// 2D array (array of arrays)
$students = [
["Alice", 25, "Computer Science"],
["Bob", 22, "Mathematics"],
["Charlie", 24, "Physics"]
];
// Accessing elements
echo "First student: " . $students[0][0] . "\n";
echo "Bob's age: " . $students[1][1] . "\n";
echo "\nAll students:\n";
foreach ($students as $student) {
echo $student[0] . " (" . $student[1] . ") - " . $student[2] . "\n";
}
echo "\n";
// Associative multidimensional array
$users = [
"user1" => [
"name" => "Alice",
"email" => "alice@example.com",
"role" => "admin"
],
"user2" => [
"name" => "Bob",
"email" => "bob@example.com",
"role" => "user"
]
];
echo "User1 name: " . $users["user1"]["name"] . "\n";
echo "User2 role: " . $users["user2"]["role"] . "\n";
echo "\nAll users:\n";
foreach ($users as $id => $user) {
echo "$id: " . $user["name"] . " (" . $user["role"] . ")\n";
}
Common Array Functions
PHP provides many built-in functions for working with arrays:
<?php
$numbers = [5, 2, 8, 1, 9, 3];
// Count elements
echo "Count: " . count($numbers) . "\n";
// Sort array
sort($numbers);
echo "Sorted: " . implode(", ", $numbers) . "\n";
// Reverse sort
rsort($numbers);
echo "Reverse sorted: " . implode(", ", $numbers) . "\n";
// Array sum
echo "Sum: " . array_sum($numbers) . "\n";
// Array max/min
echo "Max: " . max($numbers) . "\n";
echo "Min: " . min($numbers) . "\n";
echo "\n";
// Working with keys and values
$fruits = ["a" => "Apple", "b" => "Banana", "c" => "Cherry"];
echo "Keys: " . implode(", ", array_keys($fruits)) . "\n";
echo "Values: " . implode(", ", array_values($fruits)) . "\n";
// Check if value exists
if (in_array("Banana", $fruits)) {
echo "Banana found!\n";
}
// Check if key exists
if (array_key_exists("a", $fruits)) {
echo "Key 'a' exists!\n";
}
Array Manipulation
Modify arrays with these useful functions:
<?php
$stack = [1, 2, 3];
// Add to end (push)
array_push($stack, 4, 5);
echo "After push: " . implode(", ", $stack) . "\n";
// Remove from end (pop)
$last = array_pop($stack);
echo "Popped: $last\n";
echo "After pop: " . implode(", ", $stack) . "\n";
// Add to beginning
array_unshift($stack, 0);
echo "After unshift: " . implode(", ", $stack) . "\n";
// Remove from beginning
$first = array_shift($stack);
echo "Shifted: $first\n";
echo "After shift: " . implode(", ", $stack) . "\n";
echo "\n";
// Merge arrays
$arr1 = [1, 2, 3];
$arr2 = [4, 5, 6];
$merged = array_merge($arr1, $arr2);
echo "Merged: " . implode(", ", $merged) . "\n";
// Slice array
$numbers = [1, 2, 3, 4, 5, 6, 7, 8];
$slice = array_slice($numbers, 2, 4); // Start at index 2, take 4 elements
echo "Slice: " . implode(", ", $slice) . "\n";
// Filter array
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$evens = array_filter($numbers, function($n) {
return $n % 2 === 0;
});
echo "Even numbers: " . implode(", ", $evens) . "\n";
Introduction to Objects
Objects allow you to create custom data types with properties and methods:
<?php
// Define a class
class Person {
// Properties
public $name;
public $age;
// Constructor
public function __construct($name, $age) {
$this->name = $name;
$this->age = $age;
}
// Method
public function introduce() {
return "Hi, I'm " . $this->name . " and I'm " . $this->age . " years old.";
}
public function haveBirthday() {
$this->age++;
return "Happy birthday! Now " . $this->age . " years old.";
}
}
// Create objects
$person1 = new Person("Alice", 25);
$person2 = new Person("Bob", 30);
// Access properties
echo "Person 1: " . $person1->name . "\n";
echo "Person 2: " . $person2->name . "\n";
// Call methods
echo $person1->introduce() . "\n";
echo $person2->introduce() . "\n";
// Modify state
echo $person1->haveBirthday() . "\n";
Object-Oriented Examples
Here are practical examples of using objects:
<?php
// Bank Account class
class BankAccount {
private $balance;
private $accountNumber;
public function __construct($accountNumber, $initialBalance = 0) {
$this->accountNumber = $accountNumber;
$this->balance = $initialBalance;
}
public function deposit($amount) {
if ($amount > 0) {
$this->balance += $amount;
return "Deposited $$amount. New balance: $" . $this->balance;
}
return "Invalid deposit amount";
}
public function withdraw($amount) {
if ($amount > 0 && $amount <= $this->balance) {
$this->balance -= $amount;
return "Withdrew $$amount. New balance: $" . $this->balance;
}
return "Invalid withdrawal amount or insufficient funds";
}
public function getBalance() {
return $this->balance;
}
}
// Create account
$account = new BankAccount("12345", 100);
echo "Initial balance: $" . $account->getBalance() . "\n";
// Transactions
echo $account->deposit(50) . "\n";
echo $account->withdraw(30) . "\n";
echo "Final balance: $" . $account->getBalance() . "\n";
Try It Yourself
Practice with arrays and objects using these exercises:
<?php
// 1. Create and manipulate an array of shopping cart items
$cart = [
["name" => "Laptop", "price" => 999.99, "quantity" => 1],
["name" => "Mouse", "price" => 29.99, "quantity" => 2],
["name" => "Keyboard", "price" => 79.99, "quantity" => 1]
];
$total = 0;
echo "Shopping Cart:\n";
foreach ($cart as $item) {
$itemTotal = $item["price"] * $item["quantity"];
$total += $itemTotal;
echo $item["name"] . " x" . $item["quantity"] . " = $" . $itemTotal . "\n";
}
echo "Total: $" . number_format($total, 2) . "\n\n";
// 2. Find average of numbers
$scores = [85, 92, 78, 95, 88];
$average = array_sum($scores) / count($scores);
echo "Average score: " . number_format($average, 2) . "\n\n";
// 3. Remove duplicates
$numbers = [1, 2, 2, 3, 4, 4, 5];
$unique = array_unique($numbers);
echo "Original: " . implode(", ", $numbers) . "\n";
echo "Unique: " . implode(", ", $unique) . "\n\n";
// 4. Simple class for a book
class Book {
public $title;
public $author;
public $pages;
public function __construct($title, $author, $pages) {
$this->title = $title;
$this->author = $author;
$this->pages = $pages;
}
public function getInfo() {
return "\"" . $this->title . "\" by " . $this->author . " (" . $this->pages . " pages)";
}
}
$book1 = new Book("The PHP Manual", "PHP Team", 1200);
$book2 = new Book("Learning PHP", "John Doe", 350);
echo $book1->getInfo() . "\n";
echo $book2->getInfo() . "\n";
// Try creating your own arrays and classes!
Key Takeaways
- Indexed arrays use numeric indices:
[0, 1, 2, ...] - Associative arrays use named keys:
["key" => "value"] - Use
foreachto iterate over arrays efficiently - Multidimensional arrays can store complex data structures
- PHP provides many built-in array functions for common operations
- Objects combine data (properties) and behavior (methods)
- Use classes to create reusable object templates
- Objects are created with the
newkeyword - Access object properties and methods with
->
Next Steps
Congratulations! You've completed the fundamental PHP lessons. You now have a solid foundation in:
- Basic syntax and output
- Variables and data types
- Functions
- Control flow
- Arrays and objects
Continue practicing these concepts and explore PHP's vast ecosystem. Consider learning about:
- Working with forms and user input
- Database connections with PDO or MySQLi
- Building web applications with PHP frameworks
- File handling and sessions
- Error handling and debugging
Pro Tip: Arrays and objects are the foundation of most PHP applications. Practice by building small projects like a contact list, todo app, or inventory system. Combine arrays with objects to create powerful data structures. Remember that objects help organize code and make it reusable, while arrays are perfect for collections of data. Master these concepts and you'll be well-equipped to build real-world PHP applications!