array_slice


php128 apg

EXTRACT a slice of a given ARRAY.





The $offset parameter denotes the position in the $array, not the key.

If $array is shorter than the $length, then only the available array elements will be present.

If $length is omitted, then the sequence will have everything from $offset up until the end of the $array.

STRING keys are always preserved, regardless of the $preserve_keys parameter.



<?php

arr array_slice 
( arr $array , int $offset [, 
                          
int $length = NULL [, bool $preserve_keys = FALSE ]] )
 

where,

$array = The input ARRAY

$offset = The position where the sequence will start
              
( SEE the below TABLE )

$length = The length of the sequence
              
( SEE the below TABLE )

$preserve_keys = To control the reorder and reset the integer array keys
                             
( SEE the below TABLE )

?> 

$array


The input ARRAY.



$offset


The position where the sequence will start.

VALUE MEANING
$offset > 0 The sequence will start at that
offset in the $array.
$offset = 0 The sequence will start at the
beginning of the $array.
$offset < 0 The sequence will start that
far from the end of the $array.
ed48


$length


The length of the sequence.

VALUE MEANING
$length = NULL The sequence will have
the length of the $array.
$length > 0 The sequence will have up to that
many elements in it.
$length < 0 The sequence will will stop that many
elements from the end of the $array.
ed48


$preserve_keys


To control the reorder and reset the integer array indexes.

VALUE MEANING
FALSE This function will reorder
and reset the integer array indexes.
TRUE This function will not reorder
and reset the integer array indexes.
ed48


  1 EXERCISE   

<?php

$arr01 
= [ "HSK" => [ "HUE", "SATURATION", "BLACK" ], 
              
"RGBc" => [ "RED", "GREEN", "BLUE" ],  
              
"RGBt" => [ "[0,255", "[0,255]", "[0,255]"  ] ];

echo 
'The given $arr01:<br>';
print_r($arr01);
echo 
'<br><br><br>';

echo 
'offset = ';
$offset01 = mt_rand(-4, 4);
echo 
$offset01 . '<br><br>';

$length01 = NULL;
// DEFAULT

$prskey01 = FALSE; 
// DEFAULT

/* - - - - - - - - - - - - - - - - - - - - - - - -
$slc01 = array_slice($arr01, 
                                $offset01, 
                                $length01, 
                                $prskey01);
- - - - - - - - - - - - - - - - - - - - - - - - - - */

$slc01 = array_slice($arr01, $offset01);

echo 
'After array_slice($arr01, $offset01):<br>';
print_r($slc01);

?>

  2 EXERCISE   

<?php

$arr02 
= [ "HSK" => [ "HUE", "SATURATION", "BLACK" ], 
               
"RGBc" => [ "RED", "GREEN", "BLUE" ],  
               
"RGBt" => [ "[0,255", "[0,255]", "[0,255]"  ] ];

echo 
'The given $arr02:<br>';
print_r($arr02);
echo 
'<br><br><br>';

echo 
'offset = ';
$offset02 = mt_rand(-4, 4);
echo 
$offset02 . '<br><br>';

echo 
'length = ';
$length02 = mt_rand(-4, 4);
echo 
$length02 . '<br><br>';

echo 
'preserve_keys = ';
$prskey02 = TRUE;
var_dump($prskey02);
echo 
'<br><br>';

$slc02 = array_slice($arr02, 
                                
$offset02, 
                                
$length02, 
                                
$prskey02);

echo 
'After array_slice($arr01, 
                                   $offset01, 
                                   $length02, 
                                   $prskey02):<br>'
; 
print_r($slc02);

?>

  3 EXERCISE   

<?php

$arr03 
= [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

echo 
'The given $arr03<br>';
print_r($arr03);
echo 
'<br><br><br>';

echo 
'offset = ';
$offset03 = mt_rand(-5, 5);
echo 
$offset03 . '<br><br>';

echo 
'length = ';
$length03 = mt_rand(-45, 45);
echo 
$length03 . '<br><br>';

$prk03 = mt_rand(0, 1);

if(
$prk03 == 0)
{
$prskey03 = FALSE;
}
else
{
$prskey03 = TRUE;
}    

echo 
'preserve_keys = ';
var_dump($prskey03);
echo 
'<br><br>';

$slc03 = array_slice($arr03, 
                                
$offset03, 
                                
$length03, 
                                
$prskey03);

echo 
'After array_slice($arr03, 
                                   $offset03, 
                                   $length03, 
                                   $prskey03):<br>'
;
print_r($slc03);

?>

  4 EXERCISE   

<?php

$arr04d 
= array("Chastity", 
                            
"Generosity", 
                            
"Temperance", 
                            
"Diligence", 
                            
"Patience", 
                            
"Charity", 
                            
"Humility");

echo 
'The given $arr04d:<br>';
var_dump($arr04d);
echo 
'<br><br><br>'; 

echo 
'offset = '; 
$offset04d = 1; 
// Deprecating Chastity!!!!!!
echo $offset04d . '<br><br>';
 
echo 
'length = '; 
$lngt04d = mt_rand(1, 6); 
// Random choice of 1 to 6 remaining virtues
echo $lngt04d . '<br><br>'; 

echo 
'preserve_keys = '; 
$prsrv04d = false; 
// Undoing parity between indexes and elements
var_dump($prsrv04d);
echo 
'<br><br>'; 

$slc04d = array_slice($arr04d, 
                                 
$offset04d, 
                                 
$lngt04d, 
                                 
$prsrv04d);

echo 
'After array_slice($arr04d, 
                                   $offset04d, 
                                   $lngt04d, 
                                   $prsrv04d):<br>'
;
var_dump($slc04d);

?>

  5 EXERCISE   

<?php

$var_array 
= 
array(
array(),
array(
1,2,3,4,5,6,7,8,9),
array(
"One", "Two", 
                    
"Three", 
                    
"Four", 
                    
"Five"),
array(
6, "six", 7, "seven", 
                      
8, "eight", 
                      
9, "nine"),
array( 
"a" => "aaa", "A" => "AAA", 
                              
"c" => "ccc", 
                              
"d" => "ddd",
                              
"e" => "eee"),
array(
"1" => "one", "2" => "two", 
                             
"3" => "three", 
                             
"4" => "four", 
                             
"5" => "five"),
array(
1 => "one", 2 => "two", 
                          
3 => 7, 
                          
4 => "four", 
                          
5 => "five"),
array(
"f" => "fff", "1" => "one", 
                             
"" => "blank", 
                           
2.4 => "float", 
                           
"F" => "FFF",
"blank" => "", 3.7 => 3.7, 
                     
5.4 => 7, 
                       
6 => 8.6, 
                      
'5' => "Five"),
array(
12, "name", 'age', '45'),
array( array(
"oNe", "tWo", 4), 
                   array(
10, 20, 30, 40, 50), 
                   array())
);

echo 
'The given $var_array;<br>';
var_dump($var_array);
echo 
'<br><br><br>';

$num = 4;
$str = "john";

$counter = 1;
foreach (
$var_array as $sub_array)
{
/* variations with two arguments */
/* offset values >, < and = 0    */

echo"<br><br><u>Iteration: ".$counter."</u><br>";
echo
"Variation with first two Arguments:<br>";
var_dump ( array_slice($sub_array, 1) );
echo 
'<br><br>';
var_dump ( array_slice($sub_array, 0) );
echo 
'<br><br>';
var_dump ( array_slice($sub_array, -2) );

/* variations with three arguments */
/* offset value variations with length values  */
echo"<br><br><br>Variation with first three Arguments:<br>";
var_dump ( array_slice($sub_array, 1, 3) );
echo 
'<br><br>';
var_dump ( array_slice($sub_array, 1, 0) );
echo 
'<br><br>';
var_dump ( array_slice($sub_array, 1, -3) );
echo 
'<br><br>';
var_dump ( array_slice($sub_array, 0, 3) );
echo 
'<br><br>';
var_dump ( array_slice($sub_array, 0, 0) );
echo 
'<br><br>';
var_dump ( array_slice($sub_array, 0, -3) );
echo 
'<br><br>';
var_dump ( array_slice($sub_array, -2, 3) );
echo 
'<br><br>';
var_dump ( array_slice($sub_array, -2, 0 ) );
echo 
'<br><br>';
var_dump ( array_slice($sub_array, -2, -3) );

/* variations with four arguments */
/* offset value, length value 
            and preserve_key values variation */
echo"<br><br><br>Variation with first two arguments
                      with preserve_key value TRUE:<br>"
;
var_dump ( array_slice($sub_array, 1, 3, true) );
echo 
'<br><br>';
var_dump ( array_slice($sub_array, 1, 0, true) );
echo 
'<br><br>';
var_dump ( array_slice($sub_array, 1, -3, true) );
echo 
'<br><br>';
var_dump ( array_slice($sub_array, 0, 3, true) );
echo 
'<br><br>';
var_dump ( array_slice($sub_array, 0, 0, true) );
echo 
'<br><br>';
var_dump ( array_slice($sub_array, 0, -3, true) );
echo 
'<br><br>';
var_dump ( array_slice($sub_array, -2, 3, true) );
echo 
'<br><br>';
var_dump ( array_slice($sub_array, -2, 0, true) );
echo 
'<br><br>';
var_dump ( array_slice($sub_array, -2, -3, true) );
$counter++;
}

/* variation of offset 
                 and length to point to same element */
echo"<br><br><br>Typical Variation of offset 
                      and length  Arguments:<br>"
;
var_dump (array_slice($var_array[2], 1, -3, true) );
echo 
'<br><br>';
var_dump (array_slice($var_array[2], 1, -3, false) );
echo 
'<br><br>';
var_dump (array_slice($var_array[2], -3, -2, true) );
echo 
'<br><br>';
var_dump (array_slice($var_array[2], -3, -2, false) );

?>

  6 EXERCISE   

<?php

/*
 * Pass different integers 
 * as $offset argument 
 * to test how array_slice() behaves
 */

echo "Testing array_slice() : usage variations.";

$input = array ('one' => 1, 
                              
2 => 'two', 
                            
'three', 
                              
9 => 'nine', 
                        
'ten' => 10);
                        
echo 
'<br><br>The given $input:<br>';
var_dump($input);
echo 
'<br><br>';

for (
$i = -7; $i <= 7; $i++) {
    echo 
"<br><br>\$offset is $i:<br>";
    
var_dump(array_slice($input, $i));
}
echo 
"<br><br><br>\$offset is maximum integer value:<br>";
var_dump(array_slice($input, PHP_INT_MAX));

echo 
"<br><br><br>\$offset is minimum integer value:<br>";
var_dump(array_slice($input, -PHP_INT_MAX));

?>

  7 EXERCISE   

<?php

/*
 * Pass different integer values 
 * as $length argument to 
 * array_slice() to test behaviour
 */

echo "Testing array_slice() : usage variations.";

$input = array ('one' => 1, 
                   
2 => 'two', 
                   
'three', 
                   
9 => 'nine', 
             
'ten' => 10);
             
echo 
'<br><br>The given $input:<br>';
var_dump($input);

$offset = 1;

echo 
"<br><br>Offset: $offset";

for (
$i = -6; $i <= 6; $i++) {
    echo 
"<br><br>\$length is $i:<br>";
    
var_dump(array_slice($input, $offset, $i));
}
echo 
"<br><br><br>\$length is maximum integer value:<br>";
var_dump(array_slice($input, $offset, PHP_INT_MAX));

echo 
"<br><br><br>\$length is minimum integer value:<br>";
var_dump(array_slice($input, $offset, -PHP_INT_MAX));


?>

  8 EXERCISE   

<?php

/*
* Pass different data types as keys
* in an array to array_slice()
* to test how $preserve_keys treats them
*/

echo "Testing array_slice() : usage variations.";

// Initialise function arguments not being substituted
$offset = 0;
$length = 10; // to ensure all elements are displayed

//get an unset variable
$unset_var = 10;
unset (
$unset_var);

// heredoc string
$heredoc = <<<EOT
hello world
EOT;

// arrays of different data types to be passed as $input
$inputs = array(

// int data
/*1*/  
'int' => array(
0 => 'zero',
1 => 'one',
12345 => 'positive',
-
2345 => 'negative',
),

// float data
/*2*/  
'float' => array(
10.5 => 'positive',
-
10.5 => 'negative',
.5 => 'half',
),

/*3*/  'extreme floats' => array(
12.3456789000e6 => 'large',
12.3456789000E-10 => 'small',
),

// null data
/*4*/ 
'null uppercase' => array(
NULL => 'null 1',
),

/*5*/  'null lowercase' => array(
null => 'null 2',
),

// boolean data
/*6*/ 
'bool lowercase' => array(
true => 'lowert',
false => 'lowerf',
),

/*7*/  'bool uppercase' => array(
TRUE => 'uppert',
FALSE => 'upperf',
),

// empty data
/*8*/ 
'empty double quotes' => array(
"" => 'emptyd',
),

/*9*/  'empty single quotes' => array(
'' => 'emptys',
),

// string data
/*10*/ 
'string' => array(
"stringd" => 'stringd',
'strings' => 'strings',
$heredoc => 'stringh',
),

// undefined data
/*11*/ 
'undefined' => array(
@
$undefined_var => 'undefined',
),

// unset data
/*12*/ 
'unset' => array(
@
$unset_var => 'unset',
),
);

// loop through each element of $inputs 
// to check the behavior of array_slice()
$iterator = 1;
foreach(
$inputs as $type => $input) {
echo 
"<br><br>Iteration $iterator : key type is $type:<br>";
echo 
"<b>\$preserve_keys = TRUE</b><br>";
var_dump( array_slice($input, $offset, $length, true) );
echo 
"<br><b>\$preserve_keys = FALSE</b><br>";
var_dump( array_slice($input, $offset, $length, false) );
$iterator++;
};

?>

  9 EXERCISE   

<?php

/*
 * Test array_slice when passed
 * 1. a two-dimensional array as $input argument
 * 2. a sub-array as $input argument
 */

echo "Testing array_slice() : usage variations.";

$input = array ('zero', 'one', 
                   array(
'zero', 'un', 'deux'),
                   
9 => 'nine');
                   
echo 
'The given $input:<br>';
var_dump($input);


echo 
"<br><br>Slice a two-dimensional array:<br>";
var_dump(array_slice($input, 1, 3));

echo 
"<br><br>\$input is a sub-array:<br>";
var_dump(array_slice($input[2], 1, 2));


?>

  10 EXERCISE   

<?php

/*
 * Test array_slice() when:
 * 1. Passed an array of referenced variables
 * 2. $input argument is passed by reference
 */

echo "Testing array_slice() : usage variations.";

$val1 = 'one';
$val2 = 'two';
$val3 = 'three';

echo 
'<br><br>Array of 
          referenced variables ($preserve_keys = default):<br>'
;
$input = array(3 => &$val1, 2 => &$val2, 1 => &$val3);
var_dump(array_slice($input, 1, 2));

echo 
'<br><br>Change $val2 ($preserve_keys = TRUE):<br>';
$val2 = 'hello, world';
var_dump(array_slice($input, 1, 2, true));

?>

  11 EXERCISE   

<?php

/*
 * Check position of internal 
 * array pointer after calling array_slice()
 */

echo "Testing array_slice() : usage variations.";

$input = array ('one' => 'un', '
                 two' 
=> 'deux', 
                 
23 => 'twenty-three', 
                 
'zero');
                 
echo 
'The given $input:<br>';
var_dump($input);

echo 
"<br><br>Call array_slice():<br>";
var_dump($result = array_slice($input, 2));

echo 
"<br><br><br>Position of Internal Pointer in Result:<br>";
echo 
key($result) . " => " . current($result) . "<br>";
echo 
"<br>Position of Internal Pointer in Original Array:<br>";
echo 
key($input) . " => " . current ($input) . "<br>";

?>

  12 EXERCISE   

<?php

/*
 * Check that results of array_slice 
 * are correct when there are holes 
 * in buckets caused by unset()
 */

echo "Testing array_slice() : usage variations.";

function 
dump_slice(array $input, 
                                           
$offsetToUnset, 
                                      
int $offset, 
                                      
int $length) {
    unset(
$input[$offsetToUnset]);
    
var_dump(array_slice($input, $offset, $length));
    echo 
'<br><br>';
}

echo 
"<br><br>Call array_slice() 
                  on array with string keys:<br>"
;
$input = ['one' => 'un', 
               
'two' => 'deux', 
                  
23 => 'twenty-three', 
                                       
'zero'];
                                       

dump_slice($input, 'two', 0, 1);
dump_slice($input, 'two', 0, 2);
dump_slice($input, 'two', 0, 3);
dump_slice($input, 23, 1, 2);

echo 
"<br>Call array_slice() on array with packed keys:<br>";
$input = [10, 11, 12, 'thirteen'];
dump_slice($input, 0, 0, 1);
dump_slice($input, 1, 0, 1);
dump_slice($input, 1, 0, 3);
dump_slice($input, 1, -1, 1);
dump_slice($input, 1, 0, 3);
dump_slice($input, 1, -3, 3);

?>