Question

I have the following array and by using array_push & I am getting not the right result.

Array:

Array
(
    [0] => 1039
    [1] => 417
    [2] => 418
)

Array Push:

array_push($array, array("a","b","c"));

Result:

Array
(
    [0] => 1039
    [1] => 417
    [2] => 418
    [3] => Array
    (
        [0] => a
        [1] => b
        [2] => c
    )

)

I want the a,b,c append to value 417 for example .

Disirable result:

Array
(
    [1039] => 1039
    [417] => Array
    (
        [0] => a
        [1] => b
        [2] => c
    )
    [418] => 418

)

How can this be done?

SOLUTION:

$data = Array (
    0 => 1039,
    1 => 417,
    2 => 418,
 );

foreach( $data as $key => $val ) {
    $new_data[$val] = 0;
}

foreach( $new_data as $k => $v ){
    if( $k == 417 ){
        $new_data[$k] = array( 'p' => 50, 'pp' => 75 );
    }
}
print_r($new_data); 
Was it helpful?

Solution 2

use loop to display new array data

 $data = Array (
      0 => 1039,
      1 => 417,
      2 => 418,
      );

 foreach( $data as $key => $val ) {
     if ( $val == 417 ) {
         $val = array( 'a','b','c' );
     }

     $new_data = array( $key => $val );
     foreach( $new_data as $key2 => $val2 ) {
         if ( is_array( $val2 ) ) {
             $val2 = array( 417 => $val );
         }
         $new_data1 = array( $key2 => $val2 );

    print_r($new_data1);
    }
}

OTHER TIPS

It doesn't really make sense, but this will do what you show in your example:

$array[1] .= print_r(array("a","b","c"), true);

.= does string concatenation, and passing true as the second argument to print_r makes it return the string that it would have printed.

The result of this is that $array[1] is a string that begins with 417 and is followed by the printed representation of the added array. There's no actual array in there. I'm not sure what you plan to do with this, but it matches your example.

Don't use array push in this case (granted I might be missing your question)

$arr = array(1,2,3);
$arr[1] = array('a','b','c');
//would output your above example.

Just do it like this & all should work as expected:

array_push($array, "a", "b", "c");

The array_push manual page explains it best:

$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);

But if the values you are adding are in an array already, then perhaps use array_merge instead:

array_merge($array, array("a","b","c"));

My running php code:

$arr = array(0=>1039,1=>417,2=>418);
array_push($arr, array("a","b","c"));
var_dump($arr);

And var_dump($arr)

array(4) { [0]=> int(1039) [1]=> int(417) [2]=> int(418) [3]=> array(3) { [0]=> string(1) "a" [1]=> string(1) "b" [2]=> string(1) "c" } } 

Use array_splice

array_splice($your_arrray, 1, 0, array("a","b","c"));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top