views:

33

answers:

2

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.

+3  A: 

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'))));
Tatu Ulmanen
+1 Neat use of array_intersect_key() and array_flip()
Mark Baker
+1  A: 
$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;
Mark Baker
+1, for such a nice display of dynamic use of array slicing, although one have to go thoroughly to understand it first.
Knowledge Craving
Definitely easier to calculate the slice values outside of the array_slice() function; but I have to concede to Tatu's clever use of array_intersect_key() and array_flip()
Mark Baker