Knowledge Craving
Knowledge Craving

Reputation: 7993

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.

Upvotes: 2

Views: 303

Answers (2)

Mark Baker
Mark Baker

Reputation: 212522

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

Upvotes: 1

Tatu Ulmanen
Tatu Ulmanen

Reputation: 124888

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'))));

Upvotes: 3

Related Questions