How get you get element key
and value
of an at the n
position array at a particular position without loop.
Imagine
$postion = 3; // get array at 3rd position
$array = array(
"A" => "Four",
"B" => "twp",
"C" => "three",
"D" => "Four",
"E" => "Five",
"F" => "Four");
$keys = array_keys($array);
$value = array_values($array);
echo implode(array_slice($keys, $postion, 1)), PHP_EOL; // Key at 3rd posstion
echo implode(array_slice($value, $postion, 1)), PHP_EOL; // Value at n position
Output
D
Four
Issues With the method is
Why not use loop
Why not use a Database
Why not use SplFixedArray
This would have been solution but i the follow weer because am not using positive keys ( I really this is nor fair on php part)
Fatal error: Uncaught exception 'InvalidArgumentException'
with message 'array must contain only positive integer keys'
What do you mean by large data set :
1e6
or 1e7
with 512M memory limit
Am sure something like fseek
for array would do the trick .. but not sure if that exists
You can simply use . includes() method of arrays: let a = [2, 4, 6, 8, 10], b = 2; if(a. includes(b)) { // your code goes here... }
To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found. The following illustrates the syntax of the indexOf() method.
Elements in an array are obtained by using a zero-based index. That means the first element is at index 0, the second at index 1, and so on. Therefore, if the array has size N , the last element will be at index N-1 (because it starts with 0 ).
Assuming PHP 5.4, with array dereferencing:
echo $array[array_keys($array)[$position]];
In earlier versions you need to break it into two lines:
$keys = array_keys($array);
echo $array[$keys[$position]];
It would also be worth using the two-line approach in 5.4+ if you have to access multiple elements, to allow you to only call the relatively expensive array_keys()
function once. Also the dereferencing approach assumes that the specific position within the array exists, which it may not. Breaking it into multiple operations would allow you to handle that error case.
Although of course you don't ever need access to the key, you can simply do:
echo array_values($array)[$position];
// or
$values = array_values($array);
echo $values[$position];
Edit
The ArrayIterator
class can also do this for you:
$iterator = new ArrayIterator($array);
$iterator->seek($position);
echo $iterator->key(), " = ", $iterator->current(); // D = Four
This is probably the least expensive way to do this assuming it doesn't create a copy of the array in memory when you do it (still researching this element), and likely the best method for multiple accesses of arbitrary keys.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With