0

How to add a new element into one array recursively, The case like this,

$insertNew = "Another Value";

Main Array :

Array
(
   [0] => 1
   [1] => 2
   [2] => 3
   [3] => 4
)

I need an array like below becaue I want to make a insert batch in mysql

        [
          ['Another Value', 1],
          ['Another Value', 2],
          ['Another Value', 3],
          ['Another Value', 4],
        ]

Please advise.

1 Answer 1

1

Hope this simplest one will be helpful

Solution 1:

Try this code snippet here

$result=array();
$insertNew = "Another Value";
foreach($yourArray as $value)
{
    $result[]=array($insertNew,$value);
}
print_r($result);

Solution 2:

Try this code snippet here

$insertNew = "Another Value";
$result=  array_map(function($value) use ($insertNew){
    return array($insertNew,$value);
}, $array);

print_r($result);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, but too much line I guess. I do this all the time, I use forecah then so so, I dont know why people down vote my question because need more elegant way.

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.