PHP

Topic: Arrays

How to Loop through an Array?

The best way to loop through an array is to use the "foreach" statement. There are two forms of "foreach" statements:    foreach ($array as $value) {} - This gives you only one temporary variable to hold the current value in the array.    foreach ($array as $key=>$value) {} - This gives you two temporary variables to hold the current key and value in the array.Here is a PHP script on how to use "foreach" on an array:<?php $array = array("Zero"=>"PHP", "One"=>"Perl", "Two"=>"Java");$array["3"] = "C+";$array[""] = "Basic";$array[] = "Pascal";$array[] = "FORTRAN";print("Loop on value only:\n");foreach ($array as $value) {  print("$value, ");}print("\n\n");print("Loop on key and value:\n");foreach ($array as $key=>$value) {  print("[$key] => $value\n");}?>This script will print:Loop on value only:PHP, Perl, Java, C+, Basic, Pascal, FORTRAN,Loop on key and value:[Zero] => PHP[One] => Perl[Two] => Java[3] => C+[] => Basic[4] => Pascal[5] => FORTRAN

Browse random answers:

How To Create an Array?
How To Test If a Variable Is an Array?
How To Retrieve Values out of an Array?
What Types of Data Can Be Used as Array Keys?
How Values in Arrays Are Indexed?
Can You Add Values to an Array without Keys?
Can You Copy an Array?
How to Loop through an Array?
How the Values Are Ordered in an Array?
How To Copy Array Values to a List of Variables?
How To Get the Total Number of Values in an Array?
How Do You Know If a Key Is Defined in an Array?
How To Find a Specific Value in an Array?
How To Get All the Keys Out of an Array?
How To Get All the Values Out of an Array?
How To Sort an Array by Keys?
How To Sort an Array by Values?
How To Join a List of Keys with a List of Values into an Array?
How To Merge Values of Two Arrays into a Single Array?
How To Use an Array as a Queue?
How To Use an Array as a Stack?
How To Randomly Retrieve a Value from an Array?
How To Create an Array with a Sequence of Integers or Characters?
How To Pad an Array with the Same Value Multiple Times?
How To Truncate an Array?
How To Join Multiple Strings Stored in an Array into a Single String?
How To Split a String into an Array of Substring?
How To Get the Minimum or Maximum Value of an Array?
How can we know the count/number of elements of an array?
How can we know the total number of elements of Array?
Explain Creating and Naming an Array.
What are the different functions in sorting an array?
What are the different functions in sorting an array?
How come the code works, but doesn’t for two-dimensional array of mine? 
What are super global arrays?
Arrays in PHP?