Keep Moving Forward | X-Team Magazine

Fine-tuning Arrays in PHP7

Written by Deji Akala | Jun 19, 2018 4:00:00 AM

An array is a compound data type which represents an association between keys and values. In PHP, it is one of the most popular and powerful data types. There are about 80 functions for working with arrays. This feature is plagued by the same quirkiness attributed to the language as a whole.

  • inconsistent naming convention - asort is not the same pattern as array_walk. A more intuitive name is array_sort.
  • inconsistent order of arguments -
    • array_filter($array, $callback) and array_map($callback, $array).
    • strpos($haystack, $needle) and array_search($needle, $haytsack).

However, arrays are not going anywhere, and neither is their power diminished. There have been improvements in this feature in recent versions of the language. Let us take a brief look at two of them.

Constants

As of PHP 5.3 there are 2 ways of defining constants - keyword: const and function: define(). For example, const TOTAL_ITEMS = 5; and define('FUNNY_MAN', 'Mr Bean');

A major difference is that const only accepts a static scalar value (number or string as well as other constants such as TRUE, FALSE, NULL, __FILE__, etc.), while you may pass any expression to define, e.g. define('DURATION', 24 * 60 * 60);.

Then in PHP 5.6, const also accepts expressions: const DURATION = 24 * 60 * 60;. However, in PHP 7, the following are possible:

define('PREMIER_LEAGUE_TEAMS', [
  'Arsenal',
  'Chelsea',
  'Liverpool',
  'Manchester City',
  'Manchester United',
  'Tottenham Hotspur',
]);
const PREMIER_LEAGUE_TEAMS = [
  'Arsenal',
  'Chelsea',
  'Liverpool',
  'Manchester City',
  'Manchester United',
  'Tottenham Hotspur',
];

Functions

The array_column function, introduced in PHP 5.5, is another example of the progressive refinement of features in PHP 7. For example, given the array below:

    $students = [
        [
            'student_id' => 'DEN20170017',
            'firstname' => 'Ngozi',
            'lastname' => 'Chukwuemeka',
            'score' => 78,
        ],
        [
            'student_id' => 'DEN20170112',
            'firstname' => 'David',
            'lastname' => 'Babajide',
            'score' => 82,
        ],
        [
            'student_id' => 'DEN20170002',
            'firstname' => 'Usman',
            'lastname' => 'Lawal',
            'score' => 76,
        ],
        [
            'student_id' => 'DEN20170088',
            'firstname' => 'Ade',
            'lastname' => 'Ogunbameru',
            'score' => 49,
        ],
  ];

Before PHP 5.5, in order to get an array of all the score columns, one would do something like:


$scores = [];
foreach ($students as $student) {
  $scores[] = $student['score'];
}

From PHP 5.5:

$scores = array_column($students, 'score'); // [0 => 78, 1 => 82, 2 => 76, 3 => 49]

And to index a column by another column, for example:


$scores = [];
foreach ($students as $student) {
  $scores[$student['student_id']] = $student['score'];
}

The new function does this too:

$scores = array_column($students, 'score', 'student_id'); // ['DEN20170017' => 78, 'DEN20170112' => 82, 'DEN20170002' => 76, 'DEN20170088' => 49]

All well and good. What about PHP 7? Now, array_column takes an array of objects from which to pull an array of public properties:

$student1 = new stdClass();
$student1->student_id = 'DEN20170017';
$student1->firstname = 'Ngozi';
$student1->lastname = 'Chukwuemeka';
$student1->score = 78;

$student2 = new stdClass();
$student2->student_id = 'DEN20170112';
$student2->firstname = 'David';
$student2->lastname = 'Babajide';
$student2->score = 82;

$student3 = new stdClass();
$student3->student_id = 'DEN20170002';
$student3->firstname = 'Usman';
$student3->lastname = 'Lawal';
$student3->score = 76;

$student4 = new stdClass();
$student4->student_id = 'DEN20170088';
$student4->firstname = 'Ade';
$student4->lastname = 'Ogunbameru';
$student4->score = 49;

$students = [$student1, $student2, $student3, $student4];

We get exactly the same results as before with $scores = array_column($students, 'score'); and $scores = array_column($students, 'score', 'student_id');.

Note that array_column does not work recursively, i.e., it does not work with deeply-nested arrays. There are some userland implementations for PHP versions lower than PHP 5.5 with or without recursiveness. See array_column() for projects using PHP earlier than version 5.5. and PHP customized array_column function for recursion.