Showing posts with label PHP Array. Show all posts
Showing posts with label PHP Array. Show all posts

Saturday, April 13, 2013

What is array


Array is collection of same data types. In PHP, an array stores multiple values in one single variable. I.e. an array is a special variable, which can store multiple values in one single variable.



using PHP, there are three types of array.


  •  Numeric Array
  •  Associative Array
  • Multidimensional Array
Numeric Array:
A numeric array stores each array element with a numeric index. i.e.  When we create numeric array, index automatically or manually assigned for each value of array at creation time.
Define array:
    
$array_name = array (array_value1, array_value2,array_value3,array_value4,--------);

$array_name[0] = array_value0;
$array_name[1] = array_value1;
$array_name[2] = array_value2;
$array_name[3] = array_value3;
..........................
..........................
$array_name[N] = array_valuen; 

Associative Array:
An associative array, each ID key is associated with a arrayvalue. When storing data about specific named values, a numerical array is not always the best way to do it. With associative arrays we can use the values as keys and assign values to them

Syntax
$ass_array = array ( "index_Id1" => arrayvalue , "index_id1" => arrayvalue, .........);

// Declare  one- dimensional array
echo "<h3>"."This is one- dimensional array"."</h3>"."</br>";
$subject = array("Mathematics","MySQL","Physics","Chemistry","English","Sanskrit","PHP","Hindi","Geography","Civics","History","Economics","Political Science");


foreach($subject as $v)
echo $v."<br>";

or

for($i=0; $i<count($subject); $i++)
{
//print_r()

echo $subject[$i]."<br><br>";
}

// Declare two-dimensional array
       $matrix  = array
                     ( array (1,2,3),
                       array (4,5,6),
                       array (7,8,9),
    array (10,11,12)
                     );
 
  echo "<h3>"."This is two dimensional array"."</h3>"."</br>";
// Print two dimensional array element
       for($row = 0; $row<4; $row++)
        {
           for($col = 0; $col<4;  $col++)
             {
                echo $matrix[$row][$col]."\t" ."\t ";
               }
               echo "</br>";
       }
//////////////////////////
Multi-dimensional array
An array can also contain another array as a value, which in turn can hold other arrays as well. In such a way we can create two- or three-dimensional arrays:
// Declare multi-dimensional array
$organization = array (array (array ("Tech","Vikash","Gupta"),
                             array  ("Sales","Sunal","Araoa"),
                             array  ("HR", "Sudhir","Aray")
                             ),
                       array (array  ("Tech","Minku","Jain"),
                             array  ("Salesteam","Guru","Gupta"),
                             array  ("HR", "Saurabh","Sharma")
                            )
                      );






echo "<h3>"."This is multidimensional Array"."</h3>"."</br>";
                    
for($layer=0; $layer<2; $layer++)
 {
  for($row=0; $row<3; $row++)
   {
    for($col=0; $col<3; $col++)
       {
        echo $organization[$layer][$row][$col]."\t";
       }
  echo "</br>" ;
 }
 echo "</br>";
 }
 ?>
 

Thursday, March 21, 2013

Difference between for and for each loop..?


They works almost same way and same speed as foreach loop will takes time for getting next element while iterating array while for loop will takes time to re-initialize the variable.Following Difference  for and for each loop.


  1. For can be used to run statements for a fixed number of times, 
    Foreach can be used to run statements for dynamically generated arrays(may be result of database query).We can also used for loop for dynamically generated array(may be result of database query). Foreach is the ideal way to iterate dynamic array. The reason behind this, we don't know the index of array as it may be associate result from database query. So if we use foreach than it will iterate the result one by one. 
  2. Foreach will works only and only with arrays.
    For will works for any logical operation and i will continue until given condition fails.There is not much execution time difference.

  3. For loop can be more optimized if we know the count of array and index of array.
    Foreach is better when we have dynamic array without knowing index of array and size of an array.
  4. For loop executes a statement or a block of statements repeatedly until a specified expression evaluates to false. there is need to specify the loop bounds( minimum or maximum).
    int k = 0;
    for (int i = 1; i <= 5; i++) 
    { 
    k = k + i ; 
    }



    Foreach statement repeats a group of embedded statements for each element in an array or an object collection.you do not need to specify the loop bounds minimum or maximum.
    int k = 0;
    int[] tempArr = new int[] { 0, 1, 2, 3, 5, 8, 13 }; 
    foreach (int i in tempArr ) 
    { 
    k = k+ i ; 
    }

Tuesday, March 12, 2013

Php Array Functions

We can used Following  Php Array Functions.

Syntax of Array

array(  key =>  value
     , ...
     )
// key may only be an integer or string
// value may be any value of any type



List 
  1. array_change_key_case — Returns an array with all string keys lowercased or uppercased
  2. array_chunk — Split an array into chunks
  3. array_count_values — Counts all the values of an array
  4. array_diff_assoc — Computes the difference of arrays with additional index check
  5. array_diff — Computes the difference of arrays
  6. array_fill — Fill an array with values
  7. array_filter — Filters elements of an array using a callback function
  8. array_flip — Exchanges all keys with their associated values in an array
  9. array_intersect_assoc — Computes the intersection of arrays with additional index check
  10. array_intersect — Computes the intersection of arrays
  11. array_key_exists — Checks if the given key or index exists in the array
  12. array_keys — Return all the keys of an array
  13. array_map — Applies the callback to the elements of the given arrays
  14. array_merge_recursive — Merge two or more arrays recursively
  15. array_merge — Merge two or more arrays
  16. array_multisort — Sort multiple or multi-dimensional arrays
  17. array_pad — Pad array to the specified length with a value
  18. array_pop — Pop the element off the end of array
  19. array_push — Push one or more elements onto the end of array
  20. array_rand — Pick one or more random entries out of an array
  21. array_reduce — Iteratively reduce the array to a single value using a callback function
  22. array_reverse — Return an array with elements in reverse order
  23. array_search — Searches the array for a given value and returns the corresponding key if successful
  24. array_shift — Shift an element off the beginning of array
  25. array_slice — Extract a slice of the array
  26. array_splice — Remove a portion of the array and replace it with something else
  27. array_sum — Calculate the sum of values in an array.
  28. array_unique — Removes duplicate values from an array
  29. array_unshift — Prepend one or more elements to the beginning of array
  30. array_values — Return all the values of an array
  31. array_walk — Apply a user function to every member of an array
  32. array — Create an array
  33. arsort — Sort an array in reverse order and maintain index association
  34. asort — Sort an array and maintain index association
  35. compact — Create array containing variables and their values
  36. count — Count elements in a variable
  37. current — Return the current element in an array
  38. each — Return the current key and value pair from an array and advance the array cursor
  39. end — Set the internal pointer of an array to its last element
  40. extract — Import variables into the current symbol table from an array
  41. in_array — Return TRUE if a value exists in an array
  42. key — Fetch a key from an associative array
  43. krsort — Sort an array by key in reverse order
  44. ksort — Sort an array by key
  45. list — Assign variables as if they were an array
  46. natcasesort — Sort an array using a case insensitive “natural order” algorithm
  47. natsort — Sort an array using a “natural order” algorithm
  48. next — Advance the internal array pointer of an array
  49. pos — Get the current element from an array
  50. prev — Rewind the internal array pointer
  51. range — Create an array containing a range of elements
  52. reset — Set the internal pointer of an array to its first element
  53. rsort — Sort an array in reverse order
  54. shuffle — Shuffle an array
  55. sizeof — Get the number of elements in variable
  56. sort — Sort an array
  57. uasort — Sort an array with a user-defined comparison function and maintain index association
  58. uksort — Sort an array by keys using a user-defined comparison function
  59. usort — Sort an array by values using a user-defined comparison function