Slices in PHP

Our first program will demonstrate working with slices, which are an important data structure in this language. Here’s the full source code:

<?php

// Unlike arrays, slices are dynamically-sized, flexible view into the elements of an array.
// In PHP, we can simulate slices using array functions.

// Initialize an empty array
$s = [];
echo "uninit: " . json_encode($s) . " " . (empty($s) ? "true" : "false") . " " . (count($s) == 0 ? "true" : "false") . "\n";

// Create an array with initial values
$s = array_fill(0, 3, "");
echo "emp: " . json_encode($s) . " len: " . count($s) . "\n";

// We can set and get just like with arrays
$s[0] = "a";
$s[1] = "b";
$s[2] = "c";
echo "set: " . json_encode($s) . "\n";
echo "get: " . $s[2] . "\n";

// 'count' returns the length of the array
echo "len: " . count($s) . "\n";

// We can add new elements to the array
$s[] = "d";
array_push($s, "e", "f");
echo "apd: " . json_encode($s) . "\n";

// We can copy arrays
$c = $s;
echo "cpy: " . json_encode($c) . "\n";

// We can slice arrays
$l = array_slice($s, 2, 3);
echo "sl1: " . json_encode($l) . "\n";

$l = array_slice($s, 0, 5);
echo "sl2: " . json_encode($l) . "\n";

$l = array_slice($s, 2);
echo "sl3: " . json_encode($l) . "\n";

// We can declare and initialize an array in a single line
$t = ["g", "h", "i"];
echo "dcl: " . json_encode($t) . "\n";

// We can compare arrays
$t2 = ["g", "h", "i"];
if ($t == $t2) {
    echo "t == t2\n";
}

// Multi-dimensional arrays
$twoD = [];
for ($i = 0; $i < 3; $i++) {
    $innerLen = $i + 1;
    $twoD[$i] = [];
    for ($j = 0; $j < $innerLen; $j++) {
        $twoD[$i][$j] = $i + $j;
    }
}
echo "2d: " . json_encode($twoD) . "\n";

?>

To run the program, save it as slices.php and use the PHP interpreter:

$ php slices.php
uninit: [] true true
emp: ["","",""] len: 3
set: ["a","b","c"]
get: c
len: 3
apd: ["a","b","c","d","e","f"]
cpy: ["a","b","c","d","e","f"]
sl1: ["c","d","e"]
sl2: ["a","b","c","d","e"]
sl3: ["c","d","e","f"]
dcl: ["g","h","i"]
t == t2
2d: [[0],[1,2],[2,3,4]]

Note that while PHP doesn’t have a built-in slice type like some other languages, we can achieve similar functionality using array functions and operations. The array_slice() function is particularly useful for creating “slices” of arrays.

PHP arrays are very flexible and can be used to simulate various data structures. They can grow and shrink dynamically, which makes them suitable for many use cases where other languages might use dedicated slice types.

Now that we’ve seen how to work with array-like structures in PHP, we’ll look at associative arrays (maps) in the next example.