Re: another Array question

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

 



On 9/10/2012 9:41 PM, admin wrote:
Hello everyone,

	I have a very long array. I want to pull all the data from the array
from a certain position to a certain position.
$myarray = array('0'=>'me', '1'=>'you','2'=>'her','3'=>'him','4'=>'them',
'5'=>'us');
Yes I know the array above it small it's an example, mine has over 150
positions.

$foundyou = array_search('you', $myarray);
$foundthem = array_search('them', $myarray);

Now I want to take all the array positions from $foundyou to $foundthem and
put their values into a variable;
For the life of me I can't remember how I did it.

I DO NOT want to foreach over the array positions that would be
counterproductive.


Well, depends on exactly what you mean by "and put their values into a variable". Do you mean concatenate all the values into one single "flat" variable. Or do you mean to make a subset array of the values between your two points you found?


First, check out array_slice.
Second, look at join


<?php

$myarray = array(
  '0'=>'me',
  '1'=>'you',
  '2'=>'her',
  '3'=>'him',
  '4'=>'them',
  '5'=>'us',
);

$s_pos = array_search('you', $myarray);
$f_pos = array_search('them', $myarray);

# Calculate the length, it is needed by array_slice()
$length = ($f_pos - $s_pos);

$subset_array = array_slice($myarray, $s_pos, $length);

print_r($subset_array);

$all_values = join(', ', $subset_array);

echo $all_values;

?>

Obviously, you need to add in some error checking. But that should get you started.

--
Jim

--
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