Answer is not $array[0];
My array is setup as follows
$array = array();
$array[7] = 37;
$array[19] = 98;
$array[42] = 22;
$array[68] = 14;
I'm sorting the array and trying to get the highest possible match out after the sorting. So in this case $array[19] = 98;
I only need the value 98 back and it will always be in the first position of the array. I can't reference using $array[0] as the 0 key doesn't exist. Speed constraints mean I can't loop through the array to find the highest match.
There also has to be a better solution than
foreach ( $array as $value )
{
echo $value;
break;
}
$keys = array_keys($array);
echo $array[$keys[0]];
Or you could use the current() function:
reset($array);
$value = current($array);
You want the first key in the array, if I understood your question correctly:
$firstValue = reset($array);
$firstKey = key($array);
You can always do ;
$array = array_values($array);
And now $array[0] will be the correct answer.
If you want the first element you can use array_shift, this will not loop anything and return only the value.
In your example however, it is not the first element so there seems to be a discrepancy in your example/question, or an error in my understanding thereof.
If you're sorting it, you can specify your own sorting routine and have it pick out the highest value while you are sorting it.
$array = array_values($array);
echo $array[0];
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
How to change key array php from
array(
[0]=>Joni
[1]=>Jono
[2]=>Riki
[3]=>Budi
);
Change index to:
array(
[nominal]=>Joni
[nominal]=>Jono
[nominal]=>Riki
[nominal]=>Budi
);
you can make a multi-dimensional array for this purpose
$arr = array('a','b','c','d');
for($i=0;$i<count($arr);$i++){
$newArr['nominal'][$i] = $arr[$i];
}
print_r($newArr);
The expected outcome you want is not possible at all, because same indexes will be over-written in single-dimensional array.
Check this to understand what i said above:- https://eval.in/954556
Now there are 2 closer possiblities of outcomes, which i am going to mention:-
$possibility1 = [];
$possibility2 =[];
foreach($array as $arr){
$possibility1[] = ['nominal'=>$arr];
$possibility2['nominal'][] = $arr;
}
print_r($possibility1);//first closer possibility
print_r($possibility2);//second closer possibility
Output:- https://eval.in/954559
When using [] to dynamically set array values, how do you get the last key that was filled?
For example, consider:
$array[] = 'apple';
$array[] = 'banana';
$array[] = 'orange';
How do you get the last key value (in this case 2 for "orange")?
The key() function is just returning 0 no matter which line I place it after.
Please use this code:
<?php
$array[] = 'apple';
$array[] = 'banana';
$array[] = 'orange';
$count = count($array);
$last_key = $count-1;
$last_value = $array[$last_key];
?>
You can get the last key with key(), but you need to call end() first:
echo key(end($array));
An alternative solution (which is less performant) is to use array_keys() and get the last element:
echo end(array_keys($array));
you can use end function
<?php
end($array);
key($array);
or just try this
echo count($array);
end($array);
echo key($array);
is all you should need.
You could also use the purpose built array_search('orange',$array) if you already know the last value you entered and only need the key.
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
If I had an array like:
$array['foo'] = 400;
$array['bar'] = 'xyz';
And I wanted to get the first item out of that array without knowing the key for it, how would I do that? Is there a function for this?
reset() gives you the first value of the array if you have an element inside the array:
$value = reset($array);
It also gives you FALSE in case the array is empty.
PHP < 7.3
If you don't know enough about the array (you're not sure whether the first key is foo or bar) then the array might well also be, maybe, empty.
So it would be best to check, especially if there is the chance that the returned value might be the boolean FALSE:
$value = empty($arr) ? $default : reset($arr);
The above code uses reset and so has side effects (it resets the internal pointer of the array), so you might prefer using array_slice to quickly access a copy of the first element of the array:
$value = $default;
foreach(array_slice($arr, 0, 1) as $value);
Assuming you want to get both the key and the value separately, you need to add the fourth parameter to array_slice:
foreach(array_slice($arr, 0, 1, true) as $key => $value);
To get the first item as a pair (key => value):
$item = array_slice($arr, 0, 1, true);
Simple modification to get the last item, key and value separately:
foreach(array_slice($arr, -1, 1, true) as $key => $value);
performance
If the array is not really big, you don't actually need array_slice and can rather get a copy of the whole keys array, then get the first item:
$key = count($arr) ? array_keys($arr)[0] : null;
If you have a very big array, though, the call to array_keys will require significant time and memory more than array_slice (both functions walk the array, but the latter terminates as soon as it has gathered the required number of items - which is one).
A notable exception is when you have the first key which points to a very large and convoluted object. In that case array_slice will duplicate that first large object, while array_keys will only grab the keys.
PHP 7.3+
PHP 7.3 onwards implements array_key_first() as well as array_key_last(). These are explicitly provided to access first and last keys efficiently without resetting the array's internal state as a side effect.
So since PHP 7.3 the first value of $array may be accessed with
$array[array_key_first($array)];
You still had better check that the array is not empty though, or you will get an error:
$firstKey = array_key_first($array);
if (null === $firstKey) {
$value = "Array is empty"; // An error should be handled here
} else {
$value = $array[$firstKey];
}
Fake loop that breaks on the first iteration:
$key = $value = NULL;
foreach ($array as $key => $value) {
break;
}
echo "$key = $value\n";
Or use each() (warning: deprecated as of PHP 7.2.0):
reset($array);
list($key, $value) = each($array);
echo "$key = $value\n";
There's a few options. array_shift() will return the first element, but it will also remove the first element from the array.
$first = array_shift($array);
current() will return the value of the array that its internal memory pointer is pointing to, which is the first element by default.
$first = current($array);
If you want to make sure that it is pointing to the first element, you can always use reset().
reset($array);
$first = current($array);
another easy and simple way to do it use array_values
array_values($array)[0]
Just so that we have some other options: reset($arr); good enough if you're not trying to keep the array pointer in place, and with very large arrays it incurs an minimal amount of overhead. That said, there are some problems with it:
$arr = array(1,2);
current($arr); // 1
next($arr); // 2
current($arr); // 2
reset($arr); // 1
current($arr); // 1 !This was 2 before! We've changed the array's pointer.
The way to do this without changing the pointer:
$arr[reset(array_keys($arr))]; // OR
reset(array_values($arr));
The benefit of $arr[reset(array_keys($arr))]; is that it raises an warning if the array is actually empty.
Test if the a variable is an array before getting the first element. When dynamically creating the array if it is set to null you get an error.
For Example:
if(is_array($array))
{
reset($array);
$first = key($array);
}
We can do
$first = reset($array);
Instead of
reset($array);
$first = current($array);
As reset()
returns the first element of the array after reset;
You can make:
$values = array_values($array);
echo $values[0];
Use reset() function to get the first item out of that array without knowing the key for it like this.
$value = array('foo' => 400, 'bar' => 'xyz');
echo reset($value);
output //
400
Starting with PHP 7.3.0 it's possible to do without resetting the internal pointer. You would use array_key_first. If you're sure that your array has values it in then you can just do:
$first = $array[array_key_first($array)];
More likely, you'll want to handle the case where the array is empty:
$first = (empty($array)) ? $default : $array[array_key_first($array)];
You can try this.
To get first value of the array :-
<?php
$large_array = array('foo' => 'bar', 'hello' => 'world');
var_dump(current($large_array));
?>
To get the first key of the array
<?php
$large_array = array('foo' => 'bar', 'hello' => 'world');
$large_array_keys = array_keys($large_array);
var_dump(array_shift($large_array_keys));
?>
In one line:
$array['foo'] = 400;
$array['bar'] = 'xyz';
echo 'First value= ' . $array[array_keys($array)[0]];
Expanded:
$keys = array_keys($array);
$key = $keys[0];
$value = $array[$key];
echo 'First value = ' . $value;
You could use array_values
$firstValue = array_values($array)[0];
You could use array_shift
I do this to get the first and last value. This works with more values too.
$a = array(
'foo' => 400,
'bar' => 'xyz',
);
$first = current($a); //400
$last = end($a); //xyz