Announcement

Collapse
No announcement yet.

How to Define an Array in PHP Using Key Value?

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to Define an Array in PHP Using Key Value?

    Hello,

    I want to define an array in PHP using key value pairs as follows:

    $myArray = (
    'item1' => 'value1',
    'item2' => 'value2',
    'item3' => 'value3'
    );

    But whenever I need to use one of the stored value in this array using numeric index like,$myArray[1] It shows the following error:

    Notice: Undefined offset: 1
    Anyone have a solution?

  • #2
    You can use array_keys when you actually need it:

    Code:
    $arrayKeys = array_keys($myArray);
    
    echo $myArray[$arrayKeys[0]];
    Or in a foreach:

    Code:
    foreach($myArray as $key=>$value) {
    //$ key stores item1,item2,item3
    //$value stores $value1, value2,value3
    }
    Last edited by Nimbus; 02-03-16, 08:56 AM.

    Comment


    • #3
      Hi Rodney,
      You can pass your array by using array_values first to get what you want:

      echo array_values($myArray)[1];
      PHP: array_values - Manual

      array_values() returns all the values from the array and indexes numerically.

      Comment


      • #4
        @Kelvin
        Would not you convert the entire array before echoing them?

        Comment


        • #5
          Originally posted by Nimbus View Post
          @Kelvin
          Would not you convert the entire array before echoing them?
          It depends on your need. If you just need one value, then it is easier.

          Comment

          Working...
          X