Using pointers for function operations in php

The internal pointer of an array is the internal organization mechanism of the array, pointing to an element in an array. The default is to point to the first element in the array. By moving or changing the position of the pointer, you can access any element in the array. For the control of array pointers, PHP provides the following built-in functions that can be used.

 

current(): Get the content data of the current pointer position.

key(): Read the index value (key value) of the data pointed to by the current pointer.

next(): Moves the internal pointer in the array to the next cell.

prev(): Rewind the internal pointer of the array by one bit.

end(): Point the internal pointer of the array to the last element.

reset(): Move the current pointer to the first index position unconditionally.

 

These functions have only one parameter, which is the array itself to be manipulated. In the following example, these array pointer functions will be used to control the order in which the elements in the array are read. The code looks like this:

< ?php
$contact = array(
"ID" => 1,
"Name" => "Gao",
"Company" => "A Company",
"Address" => "Beijing",
"电话" => "(010)98765432",
"EMAIL" => "[email protected]",
);
 
//When the array is just declared, the array pointer is at the position of the first element in the array
echo 'The first element: '.key($contact).' => '.current($contact).'<br>'; //The first element
echo 'The first element: '.key($contact).' => '.current($contact).'<br>'; //The array pointer is not moved
 
next($contact);
next($contact);
echo 'The third element: '.key($contact).' => '.current($contact).'<br>'; //The third element
 
end($contact);
echo 'The last element: '.key($contact).' => '.current($contact).'<br>';
 
prev($contact);
echo 'The penultimate element: '.key($contact).' => '.current($contact).'<br>';
 
reset($contact);
echo 'back to the first element: '.key($contact).' => '.current($contact).'<br>';
?>

 

   In the above example, use the pointer control functions next(), prev(), end() and reset() to move the pointer position in the array at will, and then use the key() and current() functions to get the key and value of the current position in the array .

 

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326173137&siteId=291194637