Get array element after performing a function on it? - php

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

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

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

PHP: How to extract this string

Suppose I've got the following string:
) [6] => Array ( [2014-05-05 00:0] => My actual content
If I want to only be left with My actual content at the end, what is the best way to split the entire string?
Note: the words My actual content are and can change. I'm hoping to cut the string based on the second => string as this will be present at all times.
It seems you're just looking to find the first value of an array with keys you do not know. This is super simple:
Consider the following array:
$array = array(
'2014-05-22 13:36:00' => 'foo',
'raboof' => 'eh',
'qwerty' => 'value',
'8838277277272' => 'test'
);
Method #1:
Will reset the array pointer to the first element and return it.
Using reset:
var_dump( reset($array) ); //string(3) "foo"
DEMO
Method #2:
Will reset the entire array to use keys of 0, 1, 2, 3...etc. Useful if you need to get more than one value.
Using array_values:
$array = array_values($array);
var_dump( $array[0] ); //string(3) "foo"
DEMO
Method #2.5:
Will reset the entire array to use keys of 0, 1, 2, 3...etc and select the first one into the $content variable. Useful if you need to get more than one value into variables straight away.
Using list and array_values:
list( $content ) = array_values($array);
var_dump( $content ); //string(3) "foo"
DEMO
Method #3:
Arrays are iteratable, so you could iterate through it but break out immediately after the first value.
Using a foreach loop but break immediatly:
foreach ($array as $value) {
$content = $value;
break;
}
var_dump($content); //string(3) "foo"
DEMO
To Answer your question, on extracting from a string based on last 'needle'...
Okay, this is quite an arbitrary question, since it seems like you're showing us the results from a print_r(), and you could reference the array key to get the result.
However, you mentioned "... at the end", so I'm assuming My actual content is actually right at the end of your "String".
In which case there's a very simple solution. You could use: strrchr from the PHP manual - http://www.php.net/manual/en/function.strrchr.php.
So you're looking at this: strrchr($string, '=>');
Hope this answers your question. Advise otherwise if not please.
you have to use foreach loop in a foreach to get the multi dimentional array values.
foreach($value as $key){
foreach($key as $val){
echo $val;
}
}

get element N from array_count_values php

I have an array on which I did array_count_values, and then an arsort.
$a example: $a = array('ten','ten','ten','three','two',one','ten','four','four');
I want to get the first element, and tried $a[0] but this did not work.
What is the correct syntax to get the first element please?
EDIT - added array
EDIT2 - Also, underlying array not allowed to be changed because their is code following that uses the associative array...
depending on whether or not you want to alter the array, you can use array_slice() or array_shift()
you can use array_values as
$a = array_values($a);
var_dump($a[0])
Same as in your last question.
key($a); // or each() for the first key=>value pair
Or alternatively:
$k = array_keys($a);
print $k[0];
ok I used this:
$a = array('ten','ten','ten','three','two','one','ten','four','four');
$bb= array_count_values ($a);
arsort($bb);
echo reset($bb);
It only works for getting the first element...Thank you all.
These are the ways of getting the first element:
$next = $arr[0];
$next = array_shift($arr);
$next = current($arr); // if the internal cursor is at position 0

Categories