PHP one-dimensional array

Question

Answers ( 1 )

    0
    2024-01-11T18:05:24+00:00

    In PHP, a one-dimensional array is a simple list of values. Each value in the array is associated with a unique key, which can be an index or a string.

    Here's a basic overview of how to work with one-dimensional arrays in PHP:

    Creating a One-Dimensional Array

    1. Indexed Array: The keys are numeric and start at 0. Example:

      $array = array("apple", "banana", "cherry");
      // or
      $array = ["apple", "banana", "cherry"];
      
    2. Associative Array: The keys are strings. Example:

      $array = array("first" => "apple", "second" => "banana", "third" => "cherry");
      // or
      $array = ["first" => "apple", "second" => "banana", "third" => "cherry"];
      

    Accessing Elements

    • Access by Key: $value = $array["first"]; // apple

    Modifying Elements

    • Add/Modify: $array["fourth"] = "date"; // Add a new element
    • Change Value: $array["first"] = "apricot"; // Change value

    Looping Through the Array

    1. Using foreach:

      foreach ($array as $key => $value) {
          echo "$key => $value\n";
      }
      
    2. Using for (for indexed arrays):

      for ($i = 0; $i < count($array); $i++) {
          echo $array[$i]."\n";
      }
      

    Useful Functions

    • Count Elements: $length = count($array);
    • Check if Key Exists: boolval(array_key_exists("first", $array));
    • Search for Value: $key = array_search("banana", $array);

    Example Usage

    $fruits = ["apple", "banana", "cherry"];
    
    foreach ($fruits as $fruit) {
        echo $fruit . "\n";
    }
    
    // Adding a new fruit
    $fruits[] = "date";
    
    // Print the updated array
    print_r($fruits);
    

    This is a basic overview, and PHP offers many more functions and features for working with arrays. Depending on your specific needs, you might explore more advanced topics like multi-dimensional arrays, array sorting functions, and array filtering.

Leave an answer