3

Hello I have $string1, Array[] and $string2. I want to create a Arraynew[] such that

Arraynew[0]=$string1
Arraynew[1]=Array[0]
.
.
.
Arraynew[n-1]=Array[n]
Arraynew[n]=$string2

The problem being that I don't know how many elements are in Array[] since it's from parsed data that changes and also I don't know how to formulate the above correctly in PHP.

Please help me.

Thank you.

2 Answers 2

5

array_unshift() will insert one or more elements at the beginning of the array. array_push() will add one or more elements to the end of the array. So:

$new_array = $array;
array_unshift($new_array, $string1);
array_push($new_array, $string2);
Sign up to request clarification or add additional context in comments.

Comments

2

In addition to the excellent answer from cletus here are a couple of more ways:

$new_array = array($string1, $string2);
array_splice($new_array, 1, 0, $array);

// Or

$new_array = array_merge((array) $string1, $array, (array) $string2);

1 Comment

Thanks for the tips, I tried to use the array_merge function before creating the question, nice to see how to do it now.

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.