get first and last element in array - php

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

Related

PHP I don't know what difference end() makes in an array

$fruits = ['apple','cranberry','banana','cranberry'];
end($fruits);
$last_key = key($fruits);
var_dump($fruits[$last_key]) // result : cranberry
$fruits = ['apple','cranberry','banana','cranberry'];
$last_key = key($fruits);
var_dump($fruits[$last_key]) // result : apple
As you can see, the results of the two codes are different.
It seems to be the difference in the return value of end(), so I looked up the documentation.
https://www.php.net/manual/en/function.end.php
they said "Returns the value of the last element or false for empty array."
If it's like this i wondered if it was a parameter difference.
Parameters:
"The array. This array is passed by reference because it is modified by the function. This means you must pass it a real variable and not a function returning an array because only actual variables may be passed by reference."
I think I've found the answer...(...it is modified by the function.) but...
When I var_dump($fruits), there is no difference in value.
var_dump($fruits);
I do not understand it well...I'm sorry, but can explain in detail?
The end() function is an inbuilt function in PHP and is used to find the last element of the given array. The end() function changes the internal pointer of an array to point to the last element and returns the value of the last element.
<?php
// Input array
$arr = array('X', 'Y', 'Z');
// end function print the last
// element of the array.
echo end($arr);
// Output - Z
?>
Another example
<?php
// Input array
$arr = array('1', '3', '4');
// end function print the last
// element of the array.
echo end($arr)."\n";
// end() updates the internal pointer
// to point to last element as the
// current() function will now also
// return last element
echo current($arr);
?>
Output - 4
4

PHP - Get first and last key and value from array

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

How to export each subarrays as an array in PHP

is it possible that, get arrays to $value with key:
Example:
$array = Array("one"=>Array("field1"=>"value1","field2"=>"value2"),
"two"=>Array("field3"=>"value3","field4"=>"value4"));
Export arrays to value:
$first = any_main_php_function_name(0,$array);
$second = any_main_php_function_name(1,$array);
Result:
$first = Array("field1"=>"value1","field2"=>"value2");
$second = Array("field3"=>"value3","field4"=>"value4");
Basically, I wanna extract multiple array. If there is no such function (any_main_php_function_name) in PHP so How can i extract above $array.
You don't need any funtion to do that. Simply get subarrays like this:
$first = $array['one'];
$second = $array['two'];
Unless you don't know the one,two keys, then you can use array_shift to get first item (one subarray). Remember that this functions also removes returned value from root array.
array_slice does what you want
$first = array_slice($array, 0, 1);
$second = array_slice($array, 1, 1);
print_r($first);
print_r($second);
May be you can array_shift to get the element from array, Like this:
$first_element=array_shift($array);
Make sure it only removes the first element from the array and
return the value of removed element.
And if you don't want to remove the element or get the sub-array in any sequence, then you can create a function like this,
function myFunction($index,$array) {
$keys = array_keys($array);
$sub_array=$arr[$keys[$index]];
}
In above function we just get the keys in a array and then use the known index to get the sub-array using keys array.
Please check this
foreach($array["one"] as $key=>$val){
echo "key=>".$key." Values=>".$val;
}
foreach($array["true"] as $key=>$val){
echo "key=>".$key." Values=>".$val;
}

Why does Referencing to Array Elements not work in this situation?

This referencing works:
$awesome_array = array (1,2,3);
$cool_array = array (4,5,6);
$ref = &$awesome_array; // reference awesome_array
$awesome_array = $cool_array;
echo $ref; //produces (4,5,6) as expected
This referencing also works:
$array[0] = "original";
$element_reference = &$array[0]; // reference $array[0]
$array[0] = "modified";
echo $element_reference; // returns "modified" as expected.
But referencing the elements in an array does not work when you change the entire array. How do you get around this?
$array = array (1,2,3);
$new_array = array (4,5,6);
$element_reference = &$array[0]; // reference $array[0]
$array = $new_array; // CHANGE ENTIRE ARRAY
echo $element_reference; // returns 1 despite the fact that the entire array changed. I need it to return 4?
Why does it not return 4 since the array has changed? How do you reference the element so it returns 4?
The reference is to an element in the array, and not to "an index into a variable called $array". As such, none of the references (for elements in the old array) apply to the new array.
The original references still refer to the original array, and elements therein; even if the original array is no longer immediately accessible.
To refer a particular index of a variable that resolves to an array, just use a normal index operation:
$array = array (1,2,3);
$new_array = array (4,5,6);
$i = 0;
echo $array[$i]; // -> 1
$array = $new_array; // reassign variable with new array
echo $array[$i]; // -> 4

PHP - How to get the element before the last element from an array?

How can I get the element before the last element from an array in PHP5 ?
This will work even on this array:
$array[0] = "hello";
$array[5] = "how";
$array[9] = "are";
end($array);
echo prev($array); // will print "how"
The other solutions using count() are assuming that the indexes of your array go in order; by using end and prev to move the array pointer, you get the actual values. Try using the count() method on the array above and it will fail.
$array[count($array)-2]
It should be a numerically indexed array (from zero). You should have at least 2 elements for this to work. (obviously)
array_slice takes a negative offset as the second argument. This will give you a single item array containing the second last item:
$arr = array(1,2,3,4,5,6);
array_slice($arr, -2, 1);
If you just want the single value on it's own you have several options. If you don't mind using an intermediate variable you can then just get the first value with [0] or call array_pop or array_shift, they both need a variable passed by reference or you'll get warnings in strict mode.
Or you could just use array_sum or array_product, which is a bit hacky but works fine for single item arrays.
A method that will work for both associative array and numeric array is to use array_pop() to pop the element off the end of array.
$last = array_pop($array);
$second_last = array_pop($array);
// put back the last
array_push($array, $last);
All arrays have an "internal array pointer" which points to the current array element, PHP has several functions which allow you to navigate through the array and view the current elements key and value.
end() - Set the internal pointer of an array to its last element
reset() - Set the internal pointer of an array to its first element
prev() - Rewind the internal array pointer
next() - Advance the internal array pointer of an array
current() - Return the current element in an array
key() - Fetch a key from an array
each() - Return the current key and value pair from an array and advance the array cursor
These functions work whether the array is empty, sequential or associative and as an array has not been specified in the example i've assumed this must work with any array.
$array = array(
'before_last' => false,
'last' => false,
);
end($array); /*
- set pointer to last element -> $array['last']
- return new current element value if it exists, -> false
- else return FALSE
*/
prev($array); /*
- set pointer one place before current pointer -> $array['before_last']
- return new current element value if it exists, -> false
- else return FALSE
*/
if(!is_null(key($array)){ /*
- return current element key if it exists -> "before_last"
- else return NULL
*/
$before_last_element_value = current($array); /*
- return current element value if it exists, -> false
- else return FALSE
*/
}
As you can see the expected result (false) and the result for a nonexistent element is the same (FALSE) so you cannot check whether an element exists using the returned element value, an element key is different.
The key can either be an integer or a string. The value can be of any type. source
The key() returns the value of the current key if the element exists otherwise it will return NULL.
A valid key can never be NULL so if null is returned we can determine that the element does not exist.
// Indexed based array
$test = array('a','b','c','d','e');
$count = count($test);
print $test[$count-2];
// Associative Array
$months = array(
'jan'=>'January',
'feb' => 'february',
'mar' => 'March',
'apr' => 'April'
);
$keys = array_keys($months);
$count = count($keys);
print $keys[$count-2];

Categories