Tuesday, January 24, 2012

PHP array functions

PHP array  samples
 1) Desplaing the array in order, with out using sort functions
<?php
$array=array(1,20,5,16,7,19,3);
$cnt = count($array) - 1;
$FinalTemp = array();
for ($i = 0; $i <= $cnt; $i++) {
foreach($array as $key=>$value)
{
     if($value==max($array))
 {
  $sort[] = max($array);
  unset($array[$key]);
  }
}
}
 print_r($sort);
?>

2) In the main array, First delete one array values and then add other array values to the main array.
<?php
$array=array(5,4,5,7,3,6,4,1,8,4,5,6,2,1);
$delete=array(4,5,6);
$add=array(11,12,12,18);

foreach($array as $k=>$val)
{
if(in_array($val, $delete))
{
unset($array[$k]);
}
}
$result = array_merge((array)$array, (array)$add);
arsort($result);
print_r($result);
?>


3) array_count_values — Counts all the values of an array

<?php
$arr=array(a,c,k,n,n,h,r,a,a,a,c,h,b,h,k,n);
print_r(array_count_values($arr));
?>

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.