note 26786 modified in function.array-slice by vrana

From: Date: Tue, 17 Aug 2004 14:49:29 +0000
Subject: note 26786 modified in function.array-slice by vrana
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-80049@lists.php.net to get a copy of this message
This function may surprise you if you use arbitrary numeric values for keys, i.e. <?php //create an array $ar = array('a'=>'apple', 'b'=>'banana', '42'=>'pear', 'd'=>'orange'); print_r($ar); // print_r describes the array as: // Array // ( // [a] => apple // [b] => banana // [42] => pear // [d] => orange // ) //use array_slice() to extract the first three elements $new_ar = array_slice($ar, 0, 3); print_r($new_ar); // print_r describes the new array as: // Array // ( // [a] => apple // [b] => banana // [0] => pear // ) ?> The value 'pear' has had its key reassigned from '42' to '0'. When $ar is initially created the string '42' is automatically type-converted by array() into an integer. array_slice() and array_splice() reassociate string keys from the passed array to their values in the returned array but numeric keys are reindexed starting with 0. --was-- This function may surprise you if you use arbitrary numeric values for keys, i.e. //create an array $ar = array('a'=>'apple', 'b'=>'banana', '42'=>'pear', 'd'=>'orange'); print_r($ar); // print_r describes the array as: // Array // ( // [a] => apple // [b] => banana // [42] => pear // [d] => orange // ) //use array_slice() to extract the first three elements $new_ar = array_slice($ar, 0, 3); print_r($new_ar); // print_r describes the new array as: // Array // ( // [a] => apple // [b] => banana // [0] => pear // ) The value 'pear' has had its key reassigned from '42' to '0'. When $ar is initially created the string '42' is automatically type-converted by array() into an integer. array_slice() and array_splice() reassociate string keys from the passed array to their values in the returned array but numeric keys are reindexed starting with 0. http://php.net/manual/en/function.array-slice.php

« previous php.notes (#80049) next »