开发者

how to insert a new line after or before a given line number in a php array

开发者 https://www.devze.com 2022-12-09 04:11 出处:网络
I need to create a new line of data within an array where the line number = a given number pseudo code

I need to create a new line of data within an array where the line number = a given number

pseudo code

$info = array("Breakfast",开发者_开发百科 "Lunch", "Dinner");
$target = "1"; //define where i want new data, pushing other data down
$inject = "Brunch";

$newarray = somefunction($info, $target, $inject);

$newarray now looks like

[0]Breakfast
[1]Brunch
[2]Lunch
[3]Dinner


You can use the array_splice function to do so:

array_splice($info, $target, 0, $inject);

But note that array_splice modifies the original array. So you would need to copy the array first and operate on the copy:

$newarray = $info;
array_splice($newarray, $target, 0, $inject);
0

精彩评论

暂无评论...
验证码 换一张
取 消