PHP Curso

PHP Arrays: Indexed, Associative, Multidimensional, and String Functions

Tutorial de Python 3 para principiantes.

Indexed Arrays

<?php
$fruits = ["apple", "banana", "cherry"];
echo $fruits[0];          // apple
$fruits[] = "date";       // append
echo count($fruits);      // 4

// Array functions
sort($fruits);            // sort in place
$sliced = array_slice($fruits, 1, 2); // ["banana", "cherry"]
$merged = array_merge($fruits, ["elderberry"]); // merge arrays

Associative Arrays

<?php
$person = [
    "name"  => "Alice",
    "age"   => 30,
    "email" => "alice@example.com"
];

echo $person["name"];         // Alice
$person["city"] = "Moscow";   // add new key

// Check and remove
if (array_key_exists("age", $person)) {
    unset($person["age"]);
}

// Get keys and values
$keys   = array_keys($person);
$values = array_values($person);

Useful Array Functions

<?php
$nums = [3, 1, 4, 1, 5, 9, 2, 6];

echo array_sum($nums);      // 31
echo max($nums);             // 9
echo min($nums);             // 1

$unique = array_unique($nums);   // remove duplicates
$filtered = array_filter($nums, fn($n) => $n > 3); // [4, 5, 9, 6]
$doubled = array_map(fn($n) => $n * 2, $nums);

String Functions

<?php
$str = "  Hello, World!  ";

echo strlen($str);             // 18
echo strtolower($str);         // "  hello, world!  "
echo strtoupper($str);         // "  HELLO, WORLD!  "
echo trim($str);               // "Hello, World!"
echo str_replace("World", "PHP", $str); // "  Hello, PHP!  "

$parts = explode(", ", "one, two, three");  // ["one", "two", "three"]
$joined = implode(" - ", $parts);            // "one - two - three"

echo substr("Hello World", 6, 5); // "World"
echo strpos("Hello World", "World"); // 6
echo str_contains("Hello World", "World"); // true (PHP 8+)

Multidimensional Arrays

<?php
$students = [
    ["name" => "Alice", "grade" => 95],
    ["name" => "Bob",   "grade" => 82],
    ["name" => "Carol", "grade" => 91],
];

foreach ($students as $student) {
    echo "{$student['name']}: {$student['grade']}
";
}

// Sort by grade descending
usort($students, fn($a, $b) => $b["grade"] <=> $a["grade"]);