Click here to Skip to main content
15,887,676 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have the following variables:
PHP
$id = 1;
$data = [3, 17, 19, 21];

I need to create an array inserting the $id value before each value taken from $data, i.e.:
PHP
array (
  0 => 1,
  1 => 3,
  2 => 1,
  3 => 17,
  4 => 1,
  5 => 19,
  6 => 1,
  7 => 21,
)

How can I accomplish this without a loop?

What I have tried:

PHP
$id = 1;
$data = [3, 17, 19, 21];

foreach ($data as $val) {
  $array[] = $id;
  $array[] = $val;
}

It works, but I would like to find an alternative solution, like a built-in function.
Posted
Updated 11-Apr-23 0:28am

1 solution

See PHP: Arrays - Manual[^] and PHP: Array Functions - Manual[^] for all features of PHP arrays.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900