简体   繁体   中英

How to get the exact value of the last array index in PHP?

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)?

在此处输入图片说明

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'];

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`

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 .

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);

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM