Hello friends, this is my 6th tutorial of PHP and Today I am sharing the concept of using arrays in PHP. As we all know that array is a collection of homogeneous elements that are stored in contiguous memory locations. In PHP, the syntax used for creating arrays is slightly different but still is very simple.
Creating an array with homogeneous elements :
 <?php  $array1=array(10,20,30,40,50); ?>
Printing a specific element from an array :
 <?php  echo $array1[1]; ?>
Creating an array with heterogeneous elements :
 <?php  $array2=array(6,"santosh","rahul",array("x","y","z")); ?>
Accessing values from the above multidimensional heterogeneous array :
 <?php  
echo $array2[3]; // Accessing complete array inside another array.
echo $array2[3][1]; // Accessing specific element of an array inside another array.
echo $array2[1]; // Accessing a specific element from the array
?>
Changing an array element with anther value :
 <?php  $array2[3]="cat"; ?>
Creating an array with key-value pair :
 <?php  $array3=array("fname"=>"Jhon","lname"=>"Smith" ); ?>
Printing a specific element from an array created using key-value pair :
 <?php  echo $array3["fname"]; ?>
Printing entire array :
 <?php  print_r($array2); ?>
Here are some common methods for manipulating arrays in PHP that may come handy while working with arrays :
Creating array : <?php  $array1=array(10,40,30,20,50); ?>
Count : <?php  echo count($array1); ?>
Max : <?php  echo max($array1); ?>
Min : <?php  echo min($array1); ?>
Sort : <?php  echo sort($array1); print_r($array1); ?>
Reverse sort : <?php  echo rsort($array1); print_r($array1); ?>
Implode : <?php  echo $str1 = implode(" * ",$array1); ?>
Explode : <?php  echo print_r(explode(" * ",$str1)); ?>
In array : <?php  echo in_array(30,$array1); ?>

0 comments:

Post a Comment

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