Wednesday, 28 January 2015

Add & Remove Value In Array



<?php
//array_push use to add element in an array :

// define an array
$myarray = array('element1', 'element2', 'element3');

// add an element to the end
array_push($myarray, 'element4');

print_r($myarray);


//print output Array ( [0] => element1 [1] => element2 [2] => element3 [3] => element4 )

//array_pop use to remove value from an array :

// define an array
$myarray = array('element1', 'element2', 'element3'); 

// remove an element from the end
array_pop($myarray); 

print_r($myarray); 


//print output Array ( [0] => element1 [1] => element2  )

?>

Sort Array

As discussed in previous example about B.I.F (built in functions) php also have some bif for sort an  array:

  • sort() - sort arrays in ascending order
  • rsort() - sort arrays in descending order
  • asort() - sort associative arrays in ascending order, according to the value
  • ksort() - sort associative arrays in ascending order, according to the key
  • arsort() - sort associative arrays in descending order, according to the value
  • krsort() - sort associative arrays in descending order, according to the key.

Method to use them:
 declare array first , write method which one want to use eg:
sort($arrayname);
it will sort array in ascending order


Array Declaration Alternative Method

Arrays can also declare as:

<?php

// define an array
$myarray[0] = 'element1';
$myarray[1] = 'element2';
$myarray[2] = 'element3'; 

print_r($myarray);
//print output Array ( [0] => element1 [1] => element2 [2] => element3 )
 // OR

// define an array
$myarray[keyname0] = 'element1'; 
$myarray[keyname1] = 'element2'; 
$myarray[keyname2] = 'element3'; 

print_r($myarray);

//print output Array ( [0] => element1 [1] => element2 [2] => element3 )

?>

Arrays Key

In php we can also set keys for each element in array as below:

<?php

// define an array
$arraykeys = array('keyname1' => 'element1', 'keyname2' => 'element2', 'keyname3' => 'element3', 'keyetc' => 'etc..');
print_r($arraykeys); 

//print output Array ( [keyname1] => element1 [keyname2] => element2 [keyname3] => element3 [keyetc] => etc.. )

//we can also get single key as follow:

print_r($arraykeys['keyname1']); 

// print output element1



?>

Array Declaration

In php Array declare as below:

<?php

// define an array
$firstarray = array('firstelement', 'secondelement', 'thirdelement', 'etc..');
print_r($firstarray);
// printout  Array ( [0] => firstelement [1] => secondelement [2] => thirdelement [3] => etc.. )

?>