0

Currently i have an array $newArr with some elements as shown in picture below. How do I know the last digit of the array index (highlighted in yellow)?

enter image description here

This is important because, if later I wanted to insert a new record into this $newArr array, I could just

$newArr[$the_variable_that_holds_the_last_digit + 1] = ['foo', 'bar'];

otherwise the whole array overwrite if

$newArr = ['foo', 'bar'];
jkucharovic
  • 4,214
  • 1
  • 31
  • 46
begineeeerrrr
  • 323
  • 2
  • 7
  • 17

4 Answers4

3

I think you are looking for end pointer

$array = array(
    'a' => 1,
    'b' => 2,
    'c' => 3, 
);

end($array);         // it will point to last key
$key = key($array); // get the last key using `key`
Jigar Shah
  • 6,143
  • 2
  • 28
  • 41
2

I think you can try this

$array = end($newArr);

$last_index = key($array);//Its display last key of array

For more details, please follow this link.

halfer
  • 19,824
  • 17
  • 99
  • 186
AddWeb Solution Pvt Ltd
  • 21,025
  • 5
  • 26
  • 57
2

Assuming you have the numerically indexed array, the last index on your array is :

$last_index = count($newArr) -1;

if However your keys are not sequential, you can do this:

end($newArr);
$last_key = key($newArr);
Amit Joshi
  • 1,334
  • 1
  • 8
  • 10
1

If the only reason is to not overwrite the values you can use [] which means add new value.

$arr = [1,2,3,4];
var_dump($arr);

// incorrect way:
$arr = [1,2];
var_dump($arr);

//correct way
$arr = [1,2,3,4];
$arr[] = [1,2];
var_dump($arr);

See here for output: https://3v4l.org/ZTg28

The "correct way" will in the example above input a new array in the array.
If you want to add only the values you need to insert them one at the time.

$arr[] = 1;
$arr[] = 2;
Andreas
  • 23,610
  • 6
  • 30
  • 62