Konnor's Blog

Learning PHP - Part 3 - Arrays, Arrays, and more Arrays

August 18, 2019

Part 3

Laracasts main site
Laracasts - PHP for beginners

Chapters covered:

Chapter 6 - Understanding Arrays
Chapter 7 - Associative Arrays

Chapter 6 - Understanding Arrays

Looping through an array

// index.php
<?php
$names = ['Bob', 'Billy', 'Jimmy'];
foreach ($names as $name) {
echo $name . ', ';
};
// Outputs: Bob, Billy, Jimmy,

Alright, now lets break it out to the view and create a list:

// index.php
<?php
$names = ['Bob', 'Billy', 'Jimmy'];
// index.view.php
<ul>
<?php
foreach ($names as $name) {
echo "<li>$name</li>";
}
?>
<-- Alternative syntax -->
<?php foreach ($names as $name) : ?>
<!-- PHP parsing has stopped, drop to HTML -->
<li>
<!-- Start parsing PHP -->
<?= $name ?>
<!-- End parsing PHP -->
</li>
<!-- End the loop by parsing PHP again -->
<?php endforeach; ?>
</ul>

This will produce the following:


  • bob
  • billy
  • jimmy
  • bob
  • billy
  • jimmy

Chapter 7 - Associative Arrays

These appear to me to be similar to a ruby hash so here we go:

// index.php
<?php
$person = [
'age' => 23,
'hair' => 'blonde',
'career' => 'web developer'
];
require 'index.view.php';
// index.view.php
<!-- Above html omitted for brevity -->
<ul>
<?php foreach ($person as $key => $feature) : ?>
<li>
<strong><?= $key; ?>: </strong><?= $feature; ?>
</li>
<?php endforeach; ?>
</ul>
<!-- Below html omitted for brevity -->

This will produce the following:


  • age: 23
  • hair: blonde
  • career: web developer

Pushing to Arrays

// index.php
<?php
// Pushing to associative arrays
$person = [
'age' => 23,
'hair' => 'blonde',
'career' => 'web developer'
];
$person['name'] = 'Bob';
// Appends bob to $person
// Pushing to non-associative arrays
$animals = ['dog', 'cat'];
$animals[] = 'zebra';
// Appends 'zebra' to $animals

Printing Arrays

// index.php
<?php
$person = [
'age' => 23,
'hair' => 'blonde',
'career' => 'web developer'
];
$person['name'] = 'Bob';
// Will convert the array to a string then print it
var_dump($person);
// Will stop parsing after this function, will still print $person
die(var_dump($person));
// Wont get evaluated because of die();
require 'index.view.php'

Removing an item from an associative array

// index.php
<?php
// associative array
$person = [
'age' => 23,
'hair' => 'blonde',
'career' => 'web developer'
];
// Remove hair
unset($person['hair']);
/* $person = [
'age' => 23,
'career' => 'web developer'
]
*/

Homework

// homework.php
<?php
$task = [
'title' => 'Renew registration',
'due_date' => 'tomorrow',
'assigned_to' => 'Konnor',
'completed' => True
];

Links

[Follow along with my repo](https://github.com/ParamagicDev/php-for-beginners)
[Laracasts main site](https://laracasts.com)
[PHP for beginners](https://laracasts.com/series/php-for-beginners)

Written by Konnor Rogers who currently works as a paramedic looking to transition into becoming a full time software developer. You should follow him on Twitter