Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,911 questions

51,843 answers

573 users

How to insert an item at a specific position in an array with PHP

3 Answers

0 votes
$arr = [3, 8, 0, 5, 2, 8];
    
$pos = 2;
$value = 99;
 
$arr = array_merge(array_slice($arr, 0, $pos), array($value), array_slice($arr, $pos));

print_r($arr);





/*
run:

Array
(
    [0] => 3
    [1] => 8
    [2] => 99
    [3] => 0
    [4] => 5
    [5] => 2
    [6] => 8
)

*/

 



answered Jul 1, 2022 by avibootz
0 votes
$arr = [3, 8, 0, 5, 2, 8];
    
$pos = 2;
$value = 99;
 
array_splice($arr, $pos, 0, $value);

print_r($arr);





/*
run:

Array
(
    [0] => 3
    [1] => 8
    [2] => 99
    [3] => 0
    [4] => 5
    [5] => 2
    [6] => 8
)

*/

 



answered Jul 1, 2022 by avibootz
0 votes
$arr = array("php"=>"99", "c"=>"108", "c++"=>"31");
    
$pos = 2;
$value = array('java' => '101');
 
$arr = array_slice($arr, 0, $pos) + $value + array_slice($arr, $pos);
 
print_r($arr);





/*
run:

Array
(
    [php] => 99
    [c] => 108
    [java] => 101
    [c++] => 31
)

*/

 



answered Jul 1, 2022 by avibootz

Related questions

2 answers 251 views
2 answers 236 views
1 answer 151 views
1 answer 145 views
1 answer 198 views
1 answer 73 views
...