Skip to main content

Posts

Showing posts with the label array

SORTING PHP ARRAY VALUES

There may be times when you want to sort the values inside of an array. For example, suppose your array values are not in alphabetical order. Like this one: $full_name = array(); $full_name["Roger"] = "Waters"; $full_name["Richard"] = "Wright"; $full_name["Nick"] = "Mason"; $full_name["David"] = "Gilmour"; To sort this array, you just use the assort( ) function. This involves nothing more complex than typing the word asort, followed by round brackets. In between the round brackets, type in the name of your Associative array: asort( $full_name ); The letter “a” tells PHP that the array is an Associative one. (If you don’t have the “a” before “sort”, your key names will turn in to numbers!). The “a” also tells PHP to sort by the Value, and NOT by the key. In our script above, the surnames will be sorted. If you want to sort using the Key, then you can use ksort() instead. If you have a Scalar ar...

FOR EACH LOOP AND ASSOCIATIVE ARRAY

You can iterate over an associative array using for each loop like below $arr=array("one"=>1,"two"=>2,"three"=>3); foreach ($arr as $key => $value) { print "Key = " . $key . " Value = " . $value . " "; } you can get array keys by using $keys=array_keys($arr); now $keys contain array of keys;//array(“one”,”two”,”three”);

HOW TO SEARCH AN ELEMENT IN MULTIDIMENTIONAL ARRAY

How to search in multidimensional array function in_multiarray($elem, $array,&$path) { foreach($array as $key => $value) { if($array[$key] == $elem){ $path[$key]=$key;return true; } else if(is_array($array[$key])){ $path[$key]=$key; if(in_multiarray($elem, ($array[$key]),$path)){ return true; } } } return false; } $path=array(); if(in_multiarray(1212,$arr,$path)){ echo "TRUE"; print_r($arr); }else{ echo "FALSE"; }