I would like to find out how I can set the last index key (without knowing what it is in advance) in the following code that fetches a price from a SIMPLEXML response:
$product_price = $CATEGORIES->PRODUCTS->PRICES->PRICE[0]->AMOUNT;
There may be more than 1 price, so at times there are 3, at times 5 etc. But I would only like to get the last one, so the key in PRICE[0] needs to dynamically fetch the last one.
How can this be achieved?
Thanks.
You can you use end() to get last element in array.
$prices = $CATEGORIES->PRODUCTS->PRICES;
$last_price = end($prices);
$amount = $last_price->AMOUNT;
You can use array_pop()
Like this:
$array = array('a','b','c');
// This get the value and remove it from the end of the array
$test1 = array_pop($array);
// This will only get the value from the array
$array[] = $test2 = array_pop($array);
var_dump($test1); // "c"
var_dump($test2); // "b"
var_dump($array); // array('a', 'b')
Related
From a given array (eg: $_SERVER), I need to get the first and last key and value. I was trying use array_shift to get first value and key but what I get is value.
Here is the $_SERVER array:
print_r($_SERVER, true))
And I tried with:
echo array_shift($_SERVER);
With PHP >= 7.3 you can get it fast, without modification of the array and without creating array copies:
$first_key = array_key_first($_SERVER);
$first_value = $_SERVER[$first_key];
$last_key = array_key_last($_SERVER);
$last_value = $_SERVER[$last_key];
See array_key_first and array_key_last.
It's not clear if you want the value, or the key. This is about as efficient as it gets, if memory usage is important.
If you want the key, use array_keys. If you want the value, just refer to it with the key you got from array_keys.
$count = count($_SERVER);
if ($count > 0) {
$keys = array_keys($_SERVER);
$firstKey = $keys[0];
$lastKey = $keys[$count - 1];
$firstValue = $array[$firstKey];
$lastValue = $array[$lastKey];
}
You can't use $count - 1 or 0 to get the first or last value in keyed arrays.
You can do a foreach loop, and break out after the first one:
foreach ( $_SERVER as $key => $value ) {
//Do stuff with $key and $value
break;
}
Plenty of other methods here. You can pick and choose your favorite flavor there.
Separate out keys and values in separate arrays, and extract first and last from them:
// Get all the keys in the array
$all_keys = array_keys($_SERVER);
// Get all the values in the array
$all_values = array_values($_SERVER);
// first key and value
$first_key = array_shift($all_keys);
$first_value = array_shift($all_values);
// last key and value (we dont care about the pointer for the temp created arrays)
$last_key = end($all_keys);
$last_value = end($all_values);
/* you can use reset function after end function call
if you worry about the pointer */
What about this:
$server = $_SERVER;
echo array_shift(array_values($server));
echo array_shift(array_keys($server));
reversed:
$reversed = array_reverse($server);
echo array_shift(array_values($reversed));
echo array_shift(array_keys($reversed));
I think array_slice() will do the trick for you.
<?php
$a = array_slice($_SERVER, 0, 1);
$b = array_slice($_SERVER, -1, 1, true);
//print_r($_SERVER);
print_r($a);
print_r($b);
?>
OUTPUT
Array ( [TERM] => xterm )
Array ( [argc] => 1 )
DEMO: https://3v4l.org/GhoFm
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`
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);
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.
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;
I have this code to get 3 random values from my array:
$maps_clean = array_filter($find_league_maps);
$random_maps = array_rand($maps_clean,3);
$league_match_maps = ",".$maps_clean[1].",".$maps_clean[2].",".$maps_clean[3].",";
This works as long as the array has at least 3 values. Now I want to modify my code so that when I want more random values than I have in my array, it just gets new ones out of the array again. Yes, this means I can have some values more than once.
How would I do that?
You can use a simple while loop and shuffle() the array inside of it, then get as many random elements as you need with array_slice(). Now if you want more random values than you have array elements, it simple takes the entire array, goes into the next iteration and takes the rest which it needs from the new shuffled array.
Code
<?php
$arr = [1,2,3,4];
$random = 5;
$result = [];
while(count($result) != $random){
shuffle($arr);
$result = array_merge($result, array_slice($arr, 0, $random - count($result)));
}
print_r($result);
?>
You can replace the elements having the same keys of an array fill with values with your $maps_clean.
$maps_clean = array_replace(array_fill(1, 3, null), array_filter($find_league_maps));
Here array_fill returns:
array(3) {
[1]=>
NULL
[2]=>
NULL
[3]=>
NULL
}
and its elements are replaced by the elements returned by array_filter($find_league_maps) that have the same keys.
The array key is start from 0 by default so, try with
$league_match_maps = ",".$maps_clean[0].",".$maps_clean[1].",".$maps_clean[2].",";
also what is the output of count($maps_clean)?
hey there i have this array:
array(1) {
["dump"]=>
string(38) "["24.0",24.1,24.2,24.3,24.4,24.5,24.6]"
}
my question:
how to get the first and the last element out from this array, so i will have:
$firstEle = "24.0";
and
$lastEle = "24.6";
anybody knows how to get those elements from the array?
i already tried this:
$arr = json_decode($_POST["dump"], true);
$col0 = $arr[0];
$col1 = $arr[1];
$col2 = $arr[2];
$col3 = $arr[3];
$col4 = $arr[4];
$col5 = $arr[5];
$col6 = $arr[6];
i could chose $col0 and $col6, but the array could be much longer, so need a way to filter the first("24.0") and the last("24.6") element.
greetings
reset() and end() does exactly this.
From the manual:
reset(): Returns the value of the first array element, or FALSE if the array is empty.
end(): Returns the value of the last element or FALSE for empty array.
Example:
<?php
$array = array(24.0,24.1,24.2,24.3,24.4,24.5,24.6);
$first = reset($array);
$last = end($array);
var_dump($first, $last);
?>
Which outputs:
float(24)
float(24.6)
DEMO
NOTE: This will reset your array pointer meaning if you use current() to get the current element or you've seeked into the middle of the array, reset() and end() will reset the array pointer (to the beginning and to the end):
<?php
$array = array(30.0, 24.0, 24.1, 24.2, 24.3, 24.4, 24.5, 24.6, 12.0);
// reset — Set the internal pointer of an array to its first element
$first = reset($array);
var_dump($first); // float(30)
var_dump(current($array)); // float(30)
// end — Set the internal pointer of an array to its last element
$last = end($array);
var_dump($last); // float(12)
var_dump(current($array)); // float(12) - this is no longer 30 - now it's 12
You can accessing array elements always with square bracket syntax. So to get the first use 0, as arrays are zero-based indexed and count($arr) - 1 to get the last item.
$firstEle = $arr[0];
$lastEle = $arr[count($arr) - 1];
As of PHP 7.3, array_key_first and array_key_last is available
$first = $array[array_key_first($array)];
$last = $array[array_key_last($array)];
You can use reset() to get the first:
$firstEle = reset($arr);
reset() rewinds array's internal pointer to the first element and returns the value of the first array element.
And end() to get the last:
$lastEle = end($arr);
end() advances array's internal pointer to the last element, and returns its value.
For first element: current($arrayname);
For last element: end($arrayname);
current(): The current() function returns the value of the current
element in an array. Every array has an internal pointer to its
"current" element, which is initialized to the first element inserted
into the array.
end(): The end() function moves the internal pointer to, and outputs,
the last element in the array. Related methods: current() - returns
the value of the current element in an array
$array = array(24.0,24.1,24.2,24.3,24.4,24.5,24.6);
$first = current($array);
$last = end($array);
echo 'First Element: '.$first.' :: Last Element:'.$last;
Output result:
First Element: 24 :: Last Element:24.6
We can acheive the goal using array values and array key also
Example : Array Values
<?php
$array = array(24.0,24.1,24.2,24.3,24.4,24.5,24.6);
$array_values = array_values($array);
// get the first item in the array
print array_shift($array_values);
// get the last item in the array
print array_pop($array_values);
?>
Example : Array Keys
<?php
$array = array(24.0,24.1,24.2,24.3,24.4,24.5,24.6);
$array_keys = array_keys($array);
// get the first item in the array
print $array[array_shift($array_keys)];
// get the last item in the array
print $array[array_pop($array_keys)];
?>
the logic is to get last element from the elemnt after particular interval when all the elemnts are been removed. suppose there are five users and every secound user is been eliminated , then i have to find the last remaining user.
$foo = array(
'0'=>'1',
'1'=>'2',
'2'=>'3',
'3'=>'4',
'4'=>'5',
'5'=>'6'
);
now remove element indexed at 2 and reindex the array in below format.
$foo = array(
'0'=>'4',
'1'=>'5',
'2'=>'6',
'3'=>'1',
'4'=>'2',
);
You can use unset(), but you'll also need to call array_values() to force a re-index. For example:
unset($foo[2]);
$foo = array_values($foo);
The original question is a bit unclear. I understand you want to remove index X, and place all items after index X as first items in the array.
$index2remove = 2;
$newArray1 = array_slice($foo, $index2remove+1); // Get items after the selected index
$newArray2 = array_slice($foo, 0, $index2remove); // get everything before the selected index
$newArray = array_merge($newArray1, $newArray2); // and combine them
Or shorter and a bit less memory consuming (but harder to read):
$index2remove = 2;
$newArray = array_merge(
array_slice($foo, $index2remove+1), // add last items first
array_slice($foo, 0, $index2remove) // add first items last
);
You do NOT need to unset value 2 in my code, you simple slice it out. We do that with the -1 in the 2nd splice function.
If you want, you can replace $newArray = array_merge() with $foo = array_merge(), but ONLY in the second, if you dont need to save the original array.
Edit: Changed small error, thank you plain jane
Try this of which the output is given below
$foo = array('0'=>'1','1'=>'2','2'=>'3','3'=>'4','4'=>'5','5'=>'6');
//need to input this as the index of the element to be removed
$remove_index = "2";
unset($foo[$remove_index]);
$slice1 = array_slice($foo, 0, $remove_index);
$slice2 = array_slice($foo, $remove_index);
$final_output = array_merge($slice2, $slice1);
Output
Array
(
[0] => 4
[1] => 5
[2] => 6
[3] => 1
[4] => 2
)