0

This is my array:

[0] => Text1 
[1] => Text2

I want to create this:

[0] => [0] => Text1 
       [1] => Text2

This is my code but does not working good:

$final_arr = array( Text1, Text2 );
$final = array();
foreach($final_arr as $pro){
    $final[] = $pro;    
}       
return $final;

Any help?

3
  • 1
    Uh... $final = array($final_arr); Commented Nov 30, 2018 at 19:54
  • $newArray[] = $oldArray; - or in your terms: $final[] = $final_array; Commented Nov 30, 2018 at 19:55
  • Thanks, its working! Commented Nov 30, 2018 at 19:56

2 Answers 2

3

You don't really need a loop for this, you can simply add the old array to a new array, and it will keep this form.

$final_arr = array('Text1', 'Text2');
$final = array($final_arr);

Alternate syntax:

$final_arr = array('Text1', 'Text2');
$final[] = $final_arr;

If you are returning this inside a function, you don't even need to reassign it to a new variable at all.

$final_arr = array('Text1', 'Text2');
return [$final_arr]; //or array($final_arr)

Output:

Array
(
    [0] => Array
        (
            [0] => Text1
            [1] => Text2
        )

)

I suggest reading the manual regarding arrays.

Sign up to request clarification or add additional context in comments.

1 Comment

@doki Glad I could help.
2

You can just wrap your $final_arr in a new array.

$final_arr = array (Text1, Text2);
$final = array($final_arr);
return $final;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.