1.2.1348. Use array_slice()

Array_slice() is de equivalent of substr() for arrays.

array_splice() is also available, to remove a portion of array inside the array, not at the ends. This has no simple equivalent for strings.

<?php

$array = range(0, 9);

// Extract the 5 first elements
print_r(array_slice($array, 0, 5));

// Extract the 4 last elements
print_r(array_slice($array, -4));

// Extract the 2 central elements : 4 and 5
print_r(array_splice($array, 4, 2));

// slow way to remove the last elementst of an array
for($i = 0; $i < 4) {
    array_pop($array);
}

?>

See also array_slice and array_splice.

1.2.1348.1. Suggestions

  • Use array_slice()

1.2.1348.2. Specs

Short name

Performances/UseArraySlice

Rulesets

All, Analyze, CE, CI-checks, Changed Behavior

Exakat since

1.9.5

PHP Version

All

Severity

Minor

Time To Fix

Quick (30 mins)

Precision

High

Features

array

Available in

Entreprise Edition, Community Edition, Exakat Cloud