Home > Mobile >  How can I add values to the last array of ArrayList
How can I add values to the last array of ArrayList

Time:10-11

Hi there I have a long working code what adds values to the last array of an ArrayList:

$a=[["1","2","3"],["a","b","c"]];
$lastArray = array_slice($a,-1)[0]; //get Last Array
array_push($lastArray,"d","e");     //add values to Last
$a = array_slice($a,0,-1);          //remove Last Array
array_push($a,$lastArray);          //add Array to Array
print_r($a);

However this code is quite long. Does someone know a shorter code for it?

CodePudding user response:

There is no such thing as an "ArrayList" in PHP; maybe you're muddling different languages? In PHP, multidimensional arrays are just arrays which happen to have other arrays as values. Those arrays can be accessed by key, and then modified directly, so you don't need to remove and re-add the array.

As long as $a doesn't have string or non-sequential keys, you can easily determine the key for the last element and modify it like this:

$lastKey = count($a) - 1;
$a[$lastKey][] = 'new element';

(The $foo[] = $bar syntax is just a shorter way of writing array_push($foo, $bar);)

CodePudding user response:

PHP has array_key_last function that will provide you the last KEY of the given array.

You can achieve what your looking for by simply doing this

$a = [[1,2,3,4],["A","B","C"]];
array_push($a[array_key_last($a)], "D", "E");

CodePudding user response:

<?php

$a=[["1","2","3"],["a","b","c"]];
// get total elements in array
$count = count($a);
// $count-1 will get you index of last element in array
// use array_push to push the new values to the last elemnt
array_push($a[$count-1], "d", "e");
// Print the array
print_r($a);

OR

You can even achieve this without using array_push, by just using []

<?php

$a=[["1","2","3"],["a","b","c"]];
$count = count($a);
$a[$count-1][] = "d";
$a[$count-1][] = "e";
print_r($a);

Sandbox Demo

  •  Tags:  
  • php
  • Related