3. Arrays

One dimension

It is not possible to store more than one value in a single variable, unless we use an array.

An array is an ordered map where the data will have a key (key) but many values (values). For example, we could save the days of the week under the same variable name.

$semana = [
    'Monday',
    'Tuesday',
    'Wednesday',
    'Thursday',
    'Friday',
    'Saturday',
    'Sunday'
];

The values are inside brackets ([]) separated by commas. This way a marker starting from zero is automatically assigned. If I want to read each element separately I must assign the marker wrapped in brackets.

echo $semana[0]; // Monday
echo $semana[3]; // Thursday
echo $semana[6]; // Sunday

If I want to see all the content I can use PHP's native function var_dump. It will tell us the length of the array, the position of each element, its type, the length of each value and the value itself that it stores.

var_dump($semana);

/*
array(7) {
  [0] =>
  string(6) "Monday"
  [1] =>
  string(7) "Tuesday"
  [2] =>
  string(9) "Wednesday"
  [3] =>
  string(8) "Thursday"
  [4] =>
  string(6) "Friday"
  [5] =>
  string(8) "Saturday"
  [6] =>
  string(6) "Sunday"
}
*/

var_dump does not need an echo in front of it.

Use var_dump instead of print_r, it provides more information.

Inside an array any type can exist, just like a variable.

$corteIngles = [
    'Blue',
    39,
    True,
    11
];

Create

To declare an empty array we only need to create a variable to which we assign some brackets.

$planetas = [];

You can also create it with its function: $planetas = array();.

Add

And to keep adding elements.

$planetas[] = 'Mars';
$planetas[] = 'Earth';
$planetas[] = 'Venus';
var_dump($planetas);

/*
array(3) {
  [0] =>
  string(4) "Mars"
  [1] =>
  string(5) "Earth"
  [2] =>
  string(5) "Venus"
}
*/

And if we want to use a more functional-programming-oriented method, we can use array_merge to create a new array.

// Starting array
$planetas = ['Mars', 'Earth', 'Venus'];

// We add 'Mercury'
$nuevosPlanetas = array_merge($planetas, ['Mercury']);

// We see the result
var_dump($nuevosPlanetas);

/*
array(4) {
  [0]=>
  string(4) "Mars"
  [1]=>
  string(5) "Earth"
  [2]=>
  string(5) "Venus"
  [3]=>
  string(7) "Mercury"
}
*/

Spread Operator (PHP 7.4+)

Since PHP 7.4, there is a more modern and efficient alternative to array_merge: the spread operator (...). It is faster and more readable:

// Starting array
$planetas = ['Mars', 'Earth', 'Venus'];

// With spread operator
$nuevosPlanetas = [...$planetas, 'Mercury'];

var_dump($nuevosPlanetas);
/*
array(4) {
  [0]=>
  string(4) "Mars"
  [1]=>
  string(5) "Earth"
  [2]=>
  string(5) "Venus"
  [3]=>
  string(7) "Mercury"
}
*/

You can combine multiple arrays:

$terrestres = ['Earth', 'Mars'];
$gaseosos = ['Jupiter', 'Saturn'];
$todos = [...$terrestres, ...$gaseosos];
// ['Earth', 'Mars', 'Jupiter', 'Saturn']

You can also add elements in the middle:

$inicio = ['first', 'second'];
$fin = ['fourth', 'fifth'];
$completo = [...$inicio, 'third', ...$fin];
// ['first', 'second', 'third', 'fourth', 'fifth']

A very handy utility to know the length of an array is to use the count() function.

echo count($planetas);
// 3

Modify

To change a value you have to indicate the position and the new value to insert. Remember that the = symbol is actually ?

$planetas[2] = 'Saturn';

Delete

Removing an element is a bit more alien, you must use a native function called unset. Personally I think it was created by an evil being. Let me explain.

Suppose I want to destroy the Earth before man does it. It is the 2nd element, whose position is 1.

unset($planetas[1]);

Let's see what happened.

var_dump($planetas);
/*
array(2) {
  [0] =>
  string(4) "Mars"
  [2] =>
  string(5) "Venus"
}
*/

It is gone... but it messed up my positions! Let's try to do a Ctrl+Z by adding the Earth again.

// I add
$planetas[] = 'Earth';
// I show everything
var_dump($planetas);
/*
array(2) {
  [0] =>
  string(4) "Mars"
  [2] =>
  string(5) "Venus"
  [3] =>
  string(5) "Earth"
}
*/

As Jack Swigert said in Apollo 13: "-Houston, we have a problem-". Our array loses the position we deleted forever. In reality it is not a problem because the vast majority of the time we will traverse it with a loop (loop) and ignore the positions, but you must be aware of how it works so you do not run into surprises.

Nevertheless you can always ignore my words and sort it by creating a new array with a loop, wasting resources.

// I delete the Earth
unset($planetas[1]);
// I declare my new array
$planetasSinTierra = [];
// I assign it element by element
foreach ($planetas as $posicion => $nombre) {
    $planetasSinTierra[] = $nombre;
}

Playing with Strings

Look and tell me what happens.

$palabra = 'abcdef';
echo $palabra[2];
// c

What happened? Well, strings can be manipulated just like an array.

$palabra = 'abcdef';
$palabra[2] = 'Z';
echo $palabra;
// abZdef

A string behaves like an array because deep down words do not exist in programming, only sets of characters. Put another way: a string is an array of many letters.

Converting a String into an Array

At some point you will have the need to turn a text into an array by means of some separator. For example, transforming a sentence into an array split by spaces. Here is an example to do it. The secret is to use preg_split.

$frase = 'In a village of La Mancha';
$arrayDeFrase = preg_split('/[\s,]+/', $frase);
echo $arrayDeFrase[2];
// "village"
var_dump($arrayDeFrase);
/*
array(6) {
  [0] =>
  string(2) "In"
  [1] =>
  string(1) "a"
  [2] =>
  string(7) "village"
  [3] =>
  string(2) "of"
  [4] =>
  string(2) "La"
  [5] =>
  string(6) "Mancha"
}
*/

Do not use split(), the function is DEPRECATED since version 5.3.0. and it was REMOVED in version 7.0.0.

Dictionary

The keys (key) can be defined by us. This is called a dictionary.

$empleados = [
    'Juan' => 34,
    'Luisa' => 56
];

To read it will be the same way, except that we no longer have positions but our own keys.

echo $empleados['Luisa'];

When adding you will have to directly indicate the name you want to give it.

$empleados = [];
$empleados['Manolo'] = 99;
var_dump($empleados);
/*
array(1) {
  'Manolo' =>
  int(99)
}
*/

Modifying will be the same, indicating the key.

$empleados['Manolo'] = 11;
var_dump($empleados);
/*
array(1) {
  'Manolo' =>
  int(11)
}
*/

And deleting is the same way as an array.

$empleados = [];
$empleados['Manolo'] = 99;
$empleados['Juan'] = 99;
var_dump($empleados);
/*
array(2) {
  'Manolo' =>
  int(99)
  'Juan' =>
  int(99)
}
*/
unset($empleados['Manolo']);
var_dump($empleados);
/*
array(1) {
  'Juan' =>
  int(99)
}
*/

Two dimensions

At the beginning of the lesson I said that any element could be added inside an array, even... we could take it to the extreme by inserting... Another array! This is called a two-dimensional array, when an array has another array inside it.

$rizo = [
    []
]
var_dump($rizo);
/*
array(1) {
  [0] =>
  array(0) {
  }
}
*/

It has countless uses. Let's imagine you have inherited a clothing store from a rich uncle. Each product has its own barcode, price, name, color and gender.

$zara = [
    123 => [
      'nombre' => 'Plaid shirt',
      'precio' => 29.95,
      'sexo' => 'Man'
    ],
    234 => [
      'nombre' => 'Flared skirt',
      'precio' => 19.95,
      'sexo' => 'Woman'
    ],
    345 => [
      'nombre' => 'Tiny handbag',
      'precio' => 50,
      'sexo' => 'Woman'
    ]
];
var_dump($zara);
/*
array(3) {
  [123] =>
  array(3) {
    'nombre' =>
    string(11) "Plaid shirt"
    'precio' =>
    double(29.95)
    'sexo' =>
    string(3) "Man"
  }
  [234] =>
  array(3) {
    'nombre' =>
    string(12) "Flared skirt"
    'precio' =>
    double(19.95)
    'sexo' =>
    string(5) "Woman"
  }
  [345] =>
  array(3) {
    'nombre' =>
    string(12) "Tiny handbag"
    'precio' =>
    int(50)
    'sexo' =>
    string(5) "Woman"
  }
}

*/

The mechanism to manage it is the same as the dictionary, except that we must go node by node.

echo $zara[345]['nombre'];
// Tiny handbag
Activity 1
  • Save your 6 favorite movies in an array.
  • Print them in paragraphs with the following format: 'Movie: The Avengers'
  • Add the position of the movie: 'Movie 4: Godzilla'

Pro:

  • Instead of paragraphs print... a table!
  • Add a bit of CSS to improve the design. Each title must have a random color. Hint!: random_int(0, 255)
Activity 2
  • Print the numbers from 1 to 10.
  • Print the numbers from 60 to 70.
  • Print the numbers from 20 to 1.
  • Print the numbers from 1 to 1000
  • Print the multiplication table of 5.

Pro:

  • Print the multiplication table of 5 with this format: 5 x 3 = 15
  • Add up the numbers from 1 to 100.
Activity 3

I suppose the previous example is clear and you have no doubts. Prove it to me!

  • How many times does the first foreach run?
  • How many times does the second foreach run?
  • How many echos were performed? Does it match the previous answers?
  • In the example you have 2 nested loops. How many do you think can exist at most (a loop inside a loop of another loop...)?
Activity 4
  • Create a select to ask for the day of birth: 1 to 31. Use a foreach.
  • Next to it another select to ask for the month of birth: 1 to 12. Use a for.
  • And then another select to ask for the year of birth: 1900 to the current year. Use a while.

This work is under a Attribution-NonCommercial-NoDerivatives 4.0 International license.

Desafíos de programación atemporales y multiparadigmáticos

Desafíos de programación atemporales y multiparadigmáticos

Te encuentras ante un librillo de actividades, divididas en 2 niveles de dificultad. Te enfrentarás a los casos más comunes que te puedes encontrar en pruebas técnicas o aprender conceptos elementales de programación.

Buy the book

Will you buy me a coffee?

This is how I keep writing without ads or paywalls.

Comments

There are no comments yet.