RE: [PHP] another Array question
| From: | admin | Date: | Tue, 11 Sep 2012 05:08:39 +0000 |
| Subject: | RE: [PHP] another Array question | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-319033@lists.php.net to get a copy of this message | ||
Length was my problem the whole time.
Thank you very much.
Resolved
-----Original Message-----
From: Jim Lucas [mailto:lists@cmsws.com]
Sent: Tuesday, September 11, 2012 1:02 AM
To: admin
Cc: php-general@lists.php.net
Subject: Re: [PHP] another Array question
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