I think that its fairly simple to add an element to an array in PHP but the problem is how do I determine the position of an element in a PHP array ?
Also i would like to know how can i find the position of the PHP Array ? Please help me guys..
I think that its fairly simple to add an element to an array in PHP but the problem is how do I determine the position of an element in a PHP array ?
Also i would like to know how can i find the position of the PHP Array ? Please help me guys..
An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.
Use array_search( ). It returns the key of the found element or false:
$position = array_search($array, $value);
if ($position !== false) {
// the element in position $position has $value as its value in array $array
}
key() returns the index element of the current array position.If you want to get the key name by position from Array than this will be the script:
<?php
$myArray['name1']=3;
$myArray['name2']=2;
$myArray['name3']=1;
echo($myArray[1]); /* return NULL */
/* isset($myArray[1]) return false; */
/* is_null($myArray[1]) return true; */
function KeyName($myArray,$pos) {
// $pos--;
/* uncomment the above line if you */
/* prefer position to start from 1 */
if ( ($pos < 0) || ( $pos >= count($myArray) ) )
return "NULL"; // set this any way you like
reset($myArray);
for($i = 0;$i < $pos; $i++) next($myArray);
return key($myArray);
}
echo KeyName($myArray,1); // result: name2
echo KeyName($myArray,2); // result: name3
echo KeyName($myArray,3); // result: "NULL"
?>
However, because array_search () elegant studies in which the value is not found, it' s better to use array_search () instead of in_array ().
Bookmarks