From 1c77b3ab9f81de15797815119119b7e9b405c856 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20M=C3=AD=C5=A1ek?= Date: Sat, 19 Oct 2024 23:35:15 +0200 Subject: [PATCH] array_key_last() fixes https://github.com/peachpiecompiler/peachpie/issues/1148 --- src/Peachpie.Library/Arrays.cs | 2 +- tests/arrays/array_key_last_001.php | 27 +++++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 tests/arrays/array_key_last_001.php diff --git a/src/Peachpie.Library/Arrays.cs b/src/Peachpie.Library/Arrays.cs index 06118973d3..bdbe37ba5e 100644 --- a/src/Peachpie.Library/Arrays.cs +++ b/src/Peachpie.Library/Arrays.cs @@ -881,7 +881,7 @@ public static PhpValue array_key_first(PhpArray array) public static PhpValue array_key_last(PhpArray array) { var enumerator = array.GetFastEnumerator(); - if (enumerator.MovePrevious()) + if (enumerator.MoveLast()) { return PhpValue.Create(enumerator.CurrentKey); } diff --git a/tests/arrays/array_key_last_001.php b/tests/arrays/array_key_last_001.php new file mode 100644 index 0000000000..239b2aef5d --- /dev/null +++ b/tests/arrays/array_key_last_001.php @@ -0,0 +1,27 @@ + 'green', + 'banana' => 'yellow', + 'cherry' => 'red', +]; + +// Using array_key_last() to get the last key of the array +$lastKey = array_key_last($fruits); + +echo "The last key is: " . $lastKey . "\n"; +echo "The value of the last element is: " . $fruits[$lastKey] . "\n"; + +// Sample indexed array +$numbers = [10, 20, 30, 40]; + +// Using array_key_last() to get the last key of the indexed array +$lastIndex = array_key_last($numbers); + +echo "The last index is: " . $lastIndex . "\n"; +echo "The value of the last element is: " . $numbers[$lastIndex] . "\n";