简体   繁体   中英

Concatenate some Array Elements among many in PHP

I have an array "$abc" which has 9 elements, as:-

Array
(
    [a] => Jack
    [b] => went
    [c] => up
    [d] => the
    [e] => hill
    [f] => but
    [g] => never
    [h] => came
    [i] => back
)

Now I need to concat only the 4 elements starting from the "b" index to the "e" index only. But I don't know what to do. I used the "implode()" function of PHP in cases where all the array elements are concatenated.

Any help is greatly appreciated.

You need to extract the desired values first and then use implode . You could use array_slice :

echo implode(" ", array_slice($abc, 1, 4));

That would produce went up the hill .

If you need to work with the literal keys, you need to be a bit more creative. In your case it would probably best just to loop through the array and compare, but you can do something exotic also:

echo implode(" ", array_intersect_key($abc, array_flip(range('b', 'e'))));
$test = array ( 'a' => 'Jack',
                'b' => 'went',
                'c' => 'up',
                'd' => 'the',
                'e' => 'hill',
                'f' => 'but',
                'g' => 'never',
                'h' => 'came',
                'i' => 'back'
              );
$start = 'b';
$end = 'e';

$result = implode(' ',array_slice($test,array_search($start,array_keys($test)),array_search($end,array_keys($test))-array_search($start,array_keys($test))+1));
echo $result;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM