0

Since version PHP > 5.4 , the '+' is no longer can be use to combine 2 numeric key array. any alternative to combine 2 numeric key array without change the key? for example

myarray1 =  [0 => '-'];
myarray2 = [8 => 'CUACA BURUK' ,
            3 => 'JALAN SESAK' ,
            2 => 'KEMALANGAN' ,
            7 => 'KENDERAAN ROSAK' ,
            6 => 'KURSUS/BENGKEL/SEMINAR' ,
            9 => 'LAIN-LAIN' ,
            4 => 'LAWATAN TAPAK/KERJA LUAR' ,
            5 => 'MESYUARAT',
            ];

I want to create a combo box, the second array is an array that I get from my database and want to and additional blank option to user. I want retain the key and the element when merge the 2 array. If I using the array_merge, it will change the key.

2
  • 1
    somewhat confuse however: $myarray2[0]='-'; seems to be all you need Commented Oct 26, 2015 at 2:17
  • What about array_unshift? Commented Oct 26, 2015 at 2:19

2 Answers 2

3

Since you only want to add one element to the array, I suggest populating an array from the database, then using an element assignment to create the - element, like so:

$options = [ /* Values from database */ ];
$options[0] = '-';
Sign up to request clarification or add additional context in comments.

Comments

2

I'm not sure why think that. $myarray1 + $myarray2 is and always has been a union in PHP. That behavior has never changed. A union and array_merge do two very different things, however. $myarray1 + $myarray2 will add elements to $myarray1 from $myarra2 who's keys do not already exist in $myarray1. array_merge($myarray1, $myarray2) will merge all elements together if the keys are numeric and overwrite string keys.

So in your example above...

<?php
$myarray1 = [0 => '-'];
$myarray2 = [
             8 => 'CUACA BURUK',
             3 => 'JALAN SESAK',
             2 => 'KEMALANGAN',
             7 => 'KENDERAAN ROSAK',
             6 => 'KURSUS/BENGKEL/SEMINAR',
             9 => 'LAIN-LAIN',
             4 => 'LAWATAN TAPAK/KERJA LUAR',
             5 => 'MESYUARAT'
            ];

$newArray = $myarray1 + $myarray2;

var_dump($newArray);

You get...

array(9) {
  [0]=>
  string(1) "-"
  [8]=>
  string(11) "CUACA BURUK"
  [3]=>
  string(11) "JALAN SESAK"
  [2]=>
  string(10) "KEMALANGAN"
  [7]=>
  string(15) "KENDERAAN ROSAK"
  [6]=>
  string(22) "KURSUS/BENGKEL/SEMINAR"
  [9]=>
  string(9) "LAIN-LAIN"
  [4]=>
  string(24) "LAWATAN TAPAK/KERJA LUAR"
  [5]=>
  string(9) "MESYUARAT"
}

In everything from PHP 4.3.0 to PHP 7.0.0 (tested with 3v4l.org).

Comments

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.