David Willis
David Willis

Reputation: 1092

Add strings to array PHP

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.

Upvotes: 3

Views: 8633

Answers (2)

GZipp
GZipp

Reputation: 5426

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

Upvotes: 2

cletus
cletus

Reputation: 625465

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

Upvotes: 5

Related Questions