Re: another Array question

From: Date: Tue, 11 Sep 2012 05:01:57 +0000
Subject: Re: another Array question
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-319032@lists.php.net to get a copy of this message
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

« previous php.general (#319032) next »