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

$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

Related

array_shift and print_r behaving wierd in PHP

I wanted to test array_shift on a simple example:
$a = ['a', 'b', 'c', 'd'];
$rem = array_shift($a);
print_r($rem);
Which only returns me: a, instead of an array of: ['b', 'c', 'd'].
php.net docs on array_shift state the following:
array_shift() shifts the first value of the array off and returns it,
shortening the array by one element and moving everything down. All
numerical array keys will be modified to start counting from zero
while literal keys won't be affected.
This function is supposed to remove the first element and return all the rest with re-ordered keys.
Now, I copied the example from the docs site as is (tried with both [] and array()):
$stack = ["orange", "banana", "apple", "raspberry"];
$fruit = array_shift($stack);
print_r($stack);
Now this returns as expected:
Array
(
[0] => banana
[1] => apple
[2] => raspberry
)
I don't understand what just happend here or what I did wrong.
My example only differs in variable names and elements in the array.
And I hardly don't believe the issue would be because of my usage of single-quotes '.
Also, here is a demo on Sandbox.
array_shift() is a stand-alone function - you don't need to assign it to a value, it automatically unsets it from the given variable:
<?php
$a = ['a', 'b', 'c', 'd'];
array_shift($a);
print_r($a);
https://3v4l.org/GEr3g
array_shift() shifts the first value of the array off and returns it
The "it" refers to "the first value", not to "the array". It shifts off the first value and returns said first value; the array is being shortened by that process. Pay close attention to what is being returned in the example code ($fruit) and what you print ($stack).
To leave the original array intact and return a new, shorter array, you'd do:
$rem = array_slice($a, 1);
In you example $rem is the return from the function array_shift as stated on the doc it will return the eliminated index value, on the other side whenever you print
print_r($a);
This will return the array after the function performed.
As the php doc array_shift shows.
The return result of array_shift is the first value of the array that been shifted off, and remove the first value of the original array.
array_shift ( array &$array ) : mixed
array_shift() shifts the first value of the array off and returns it,
shortening the array by one element and moving everything down. All
numerical array keys will be modified to start counting from zero
while literal keys won't be affected.

PHP Single line array shuffle is not working

Very simple but I was wondering why this is not working.
I'm trying shuffle an array and output the results (in a single line structure)
this is my code :
echo shuffle(array("A","B","C"))[0];
Small tweak needed here ;)
Your basic logic is a little bit wrong. You're interested in only one value, I assume? To solve it with that logic in mind, you can do it like this:
echo array_rand(array_flip(['A', 'B', 'C']));
Try below code
$arr = array("A","B","C");
shuffle($arr);
echo $arr[0];
I know that this is not the best solution for you, but it works!
print_r( ( $b=array('A', 'B', 'C') ) && shuffle($b) ? next($b) : null );
How this works:
Assign the array to the variable $b
Shuffle the variable $b
If the shuffle() succeeded:
return the next element in the array
If the shuffle() failed:
return null
Some might think: "Why didn't he used the current() function?"
Well, it seems that the function shuffle simply changes the order of the keys, but the pointer is always pointing to the same element. This means that current() will always return 'A'.
Apparently, this behaviour changed on PHP 5.4 to set the pointer to the first element.
TRY THIS SIMPLE FUNCTION
$my_array = array("A","B","C","D","E");
shuffle($my_array);
print_r($my_array);
You will need to pass the array in a seperate variable. Also, shuffle() itself just returns a boolean value, so you need to return an array element instead of the output of the function.
$ar = array("A","B","C");
shuffle($ar);
echo $ar[0];

get first and last element in array

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

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

Get array element after performing a function on it?

I'm looking to see if there is some PHP syntax that I'm missing that will allow me to grab the contents of the array I just manipulated using a function..
Good example:
$firstElement = sort($myArray)[0];
Where normally I would have to do this:
$myArray = sort($myArray);
$firstElement = $myArray[0];
Any clean way of doing this??
Thanks Everyone!
Matt
There is no syntax to access an array value if it’s not in a variable. There was a proposal to add such a syntax but it was declined.
PS: sort does only return boolean values. So your example wouldn’t work anyway.
A syntax like this one
$firstElement = sort($myArray)[0];
is definitly nont possible -- you have noticed that yourself ^^
If you are willing to get the first element of an array, you could use the reset function, like this :
$list = array('z', 'c', 'd');
$element = reset($list);
var_dump($element);
It would display :
string 'z' (length=1)
The side-effect is that (quote) :
reset() rewinds array 's internal
pointer to the first element and
returns the value of the first array
element.
Btw, as sort doesn't return the array, you cannont do that :
$list = array('z', 'c', 'd');
$element = reset(sort($list));
var_dump($element);
It would give a warning :
Warning: reset() [function.reset]:
Passed variable is not an array or
object

Categories