How to Convert a PHP Array Key to Numbers

Each element in a PHP array is assigned an index number. Using the count functions available for PHP arrays, you can determine the number of array values and the index number associated with the value. You must use the PHP foreach function to step through each value and return the index number. This type of programming is typically used when you want to display each value to users and list its corresponding number.

Instructions

    • 1

      Right-click the PHP file you want to edit and select "Open With." Double-click the editing program you use to create PHP files.

    • 2

      Create the array if you do not already have an array set up. The following code shows you how to create an array that holds three values:

      array(0 => 'Blue', 1 => 'Brown', 2 => 'Purple');

      The array contains three colors marked with index numbers zero to two.

    • 3

      Loop through each array value and print out the array's index number. The following code shows you how to convert the value to the associated index number:

      foreach($arr as $key => $color)

      {

      echo "$color index number:($key)";

      }

      The foreach statement evaluates each value in the array and prints out the number. In this array, the printed output is "1," "2" and "3."

Related Searches:

References

Comments

Related Ads

Featured