RE: Array Slice without loosing index

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Notice that the fourth parameter of array_slice will only work in PHP 5, and
not for string keys.
There's no associative array slicing function that I know of (it would be a
good idea for PHP to incorporate one), so I use the following two, which
work for numeric or string keys, and work for PHP 4 or 5.

function xarray_slice_assoc($array, $keys) {
  /* TODO: Error Handling */
  $result = array();
  foreach ($keys as $key):
    // You can use array_key_exists instead of isset to allow for NULLs and
avoid PHP Notices
    if (isset($array[$key])):
      $result[$key] = $array[$key];
    endif;
  endforeach;
  return $result;
}

function xslice_assoc() {
  /* TODO: Error Handling */
  $args = func_get_args();
  $array = array_shift($args);
  return xarray_slice_assoc($array, $args);
}

You can call them like this:

$userLogin = xslice_assoc($_REQUEST, 'user', 'password');
// $userLogin is now an array with "user" and "password" fields, or only
"user", or only "password" or an empty array

$someRecords = xarray_slice_assoc($someRecordset, array(1, 25, 32, 4));
// $someRecors will contain records number 1, 25, 32 and 41 if they exist

Rob


Andrés Robinet | Lead Developer | BESTPLACE CORPORATION
5100 Bayview Drive 206, Royal Lauderdale Landings, Fort Lauderdale, FL 33308
| TEL 954-607-4207 | FAX 954-337-2695
Email: info@xxxxxxxxxxxxx  | MSN Chat: best@xxxxxxxxxxxxx  |  SKYPE:
bestplace |  Web: http://www.bestplace.biz | Web: http://www.seo-diy.com

> -----Original Message-----
> Hi all,
> 
> I am wanting to retain the array indexes after it being sliced. Here is
> what I
> have so far.
> 
> if ($user_count > $group_count)
> {
> 	for ($i = 0; $i < $user_count; $i+=$group_count)
> 	{
> 		$output = array_slice($properties['users'], $i,
> $group_count);
> 		print_r($output);
> 	}
> }
> 
> Every time the array is sliced it results with arrays which have new
> idexes.
> Is there a way I can retain the array indexes when slicing the array.
> 
> regards,
> Jeffery
> --
> Internet Vision Technologies
> Level 1, 520 Dorset Road
> Croydon
> Victoria - 3136
> Australia
> web: http://www.ivt.com.au
> phone: +61 3 9723 9399
> fax: +61 3 9723 4899
> 
> --
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php



[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux