note 124257 added to function.array-push
| From: | siqueiramoises14 at gmail dot com | Date: | Wed, 02 Oct 2019 01:07:04 +0000 |
| Subject: | note 124257 added to function.array-push | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-212448@lists.php.net to get a copy of this message | ||
if you need to push a multidimensional numeric array into another, array push will push the hole
array into a key of the first array, for example, let's imagine you have two arrays:
<?php
$array1 = [
0 => [
"key1" => "value1",
"key2" => "value2"
]
];
$array2 = [
0 => [
"key1" => "value1",
"key2" => "value2"
]
];
$array1[] = $array2;
//after that array1 will look like this:
[
0 => [
"key1" => "value1",
"key2" => "value2"
],
1 => [
0 => [
"key1" => "value2",
"key2" => "value2"
]
]
// If you don't want that to happen here's a function to avoid that:
function array_push_indexes($array1, $array2){
$lastKey = array_key_last($array1);
for($i = 0; $i < count($array2); $i++){
$KeyPosition = 1 + $i;
$array1[$lastKey+$KeyPosition] = $array2[$i];
}
return $array1;
}
//Using the same example from before this function will return:
[
0 => [
"key1" => "value1",
"key2" => "value2"
],
1 => [
"key1" => "value1",
"key2" => "value2"
]
]
?>
P.S: the array_key_last function it's for PHP >= 7.3.0 see more here https://www.php.net/manual/en/function.array-key-last.php
----
Server IP: 208.43.231.9
Probable Submitter: 82.199.157.54 (proxied: 179.232.98.105)
----
Manual Page -- http://php.net/manual/en/function.array-push.php
Edit -- https://master.php.net/note/edit/124257
Del: integrated -- https://master.php.net/note/delete/124257/integrated
Del: useless -- https://master.php.net/note/delete/124257/useless
Del: bad code -- https://master.php.net/note/delete/124257/bad+code
Del: spam -- https://master.php.net/note/delete/124257/spam
Del: non-english -- https://master.php.net/note/delete/124257/non-english
Del: in docs -- https://master.php.net/note/delete/124257/in+docs
Del: other reasons-- https://master.php.net/note/delete/124257
Reject -- https://master.php.net/note/reject/124257
Search -- https://master.php.net/manage/user-notes.php