This commit is contained in:
2026-03-06 21:27:16 -05:00
parent 1fdfbb1b4f
commit 41ebd4ac62
21 changed files with 1018 additions and 43 deletions
+194
View File
@@ -0,0 +1,194 @@
<?php
/* Arrays */
$months = array(
'January', // Index = 0
'February', // Index = 1
'March', // Index = 2
);
echo '<pre>';
print_r($months);
echo '</pre>';
// Getting value from index
echo '<pre>';
print_r($months[1]);
echo '</pre>';
// Short hand
$months = [
'January', // Index = 0
'February', // Index = 1
'March', // Index = 2
];
/* Associative Arrays */
$months = [
'month1' => 'January',
'month2' => 'February',
'month3' => 'March'
];
echo '<pre>';
print_r($months);
echo '</pre>';
echo '<pre>';
print_r($months['month1']);
echo '</pre>';
/* Working with Arrays */
// range()
$numbers = range(1, 10); // Same as $numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
echo '<pre>';
print_r($numbers);
echo '</pre>';
$numbers = range(1, 10, 2); // Same as $numbers = [1, 3, 5, 7, 9];
echo '<pre>';
print_r($numbers);
echo '</pre>';
// Adding to arrays
$months = [
'January', // Index = 0
'February', // Index = 1
'March', // Index = 2
];
// Add to index 3
$months[3] = 'April';
// Change index 2
$months[2] = 'May';
// Add to end of array
$months[] = 'June';
echo '<pre>';
print_r($months);
echo '</pre>';
/* Merging Arrays */
$sem1grades = [
'math' => 90,
'chemistry' => 67,
'biology' => 88,
'history' => 45,
'gym' => 60,
];
$sem2grades = [
'philosophy' => 87,
'art' => 99,
'physics' => 71,
'gym' => 60,
];
// array_merge()
$allGrades = array_merge($sem1grades, $sem2grades);
echo '<pre>';
print_r($allGrades);
echo '</pre>';
// Array Union
$allGrades = $sem1grades + $sem2grades;
echo '<pre>';
print_r($allGrades);
echo '</pre>';
/* Multidimensional arrays */
$meats = [
'Pepperoni',
'Bacon',
'Ham',
];
$cheeses = [
'Mozzarella',
'Cheddar',
'Swiss',
];
$veggies = [
'Onions',
'Peppers',
'Mushrooms',
];
$toppings = [
'Meats' => $meats,
'Cheeses' => $cheeses,
'Veggies' => $veggies,
'Size' => 'Medium',
];
echo $toppings['Veggies'][1];
echo '<br><br>';
/* Printing Arrays */
// foreach()
foreach ($toppings as $type => $value) {
echo "{$type}:</br>";
if (is_array($value)) {
foreach ($value as $number => $topping) {
echo "Topping #{$number} is $topping</br>";
}
}
else {
echo "{$type} is $value</br>";
}
echo "</br>";
}
$words = [
'The',
'cow',
'jumped',
'over',
'the',
'moon',
];
// implode()
$sentence = implode(' ', $words);
echo $sentence;
echo '<br><br>';
// explode()
$words2 = explode(' ', $sentence);
echo $words2;
echo '<br><br>';
/* Sorting Arrays */
$array1 = [
3,
1,
4,
1,
5,
9,
];
// sort()
sort($array1);
echo '<pre>';
print_r($array1);
echo '</pre>';
// rsort()
rsort($array1);
echo '<pre>';
print_r($array1);
echo '</pre>';
$assocArray = [
'a' => 3,
'b' => 1,
'c' => 4,
];
// asort()
asort($assocArray);
echo '<pre>';
print_r($assocArray);
echo '</pre>';
$assocArray = [
'a' => 3,
'b' => 1,
'c' => 4,
];
// ksort()
ksort($assocArray);
echo '<pre>';
print_r($assocArray);
echo '</pre>';