0

Im looking for a way to take a php array and pass the values between a couple of array keys and save into a string.

$array1 = array(0=>'sometext',
                1=>'1703',
                2=>'North',
                3=>5th',
                4=>'st',
                5=>'sometext')


I know the starting key and the end key in my script
$startnum = 1;
$endnum  = 4;
I need to get this
$string = '1703 North 5th st'

without changing the keys in the array because i have to iterate over the array again later. I am currently using array splice but it removes the items and key in the array so when i iterate over the array again the keys and values are all messed up. Please let me know if i need a better explanation.

0

2 Answers 2

8

Get the segment of interest using array_slice, then collapse it using implode:

$string = implode(' ', array_slice($array1, $startnum, $endnum-$startnum));

Note that array_slice takes an offset and a length, so the length is computed as the end less the start.

Sign up to request clarification or add additional context in comments.

Comments

3

You could always use a basic for loop:

$str = "";
for ($i = $startnum; $i < $endnum; $i++){
    $str .= $array1[$i]." ";
}
$str .= $array1[$endnum];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.