treehouse : what would you like to learn today?
Web Design Web Development iOS Development

[Solved] How do I get each value of an array and put it in separate variables.

  • Hi guys, can anyone please help me out: How do I get each value of an array and put it in separate variables.

    here's the array:

    Array ( [0] => 1946 [1] => 6 [2] => 10 ) 
    

    This is a birthday in an array, I'd like to get each value and put it in 3 variables which is the $Year, $Month, $Day. So I can output it as "Month Day, Year".

    Please please help. Thanks.

  • Your array declaration is invalid. If you make it like:

      array(1946, 6, 10);
    

    or

      array(0 => 1946, 1 => 6, 2 => 10);
    

    if you must, you can then use

      $year = $whatever_array[0];
    
  • Actually got an answer for this problem. :D

    $selectbirthday = array ( [0] => 1946 [1] => 6 [2] => 10 );
    
    $resultyear = $selectbirthday[0];
    
    echo $resultyear;
    

    output is: 1946

  • Really? What PHP version do you use because I definitely getting an error on that array syntax (PHP Version 5.3.13)

  • @CrocoDillon, what you posted recently was correct. I actually forgot to mention that I fetched the values of the array from a database field and used "explode()" function to reference them individually. This is actually the output when I print_r "array ( [0] => 1946 [1] => 6 [2] => 10 );"

    But this is the correct way:

    $selectbirthday = array( 0 => 1946, 1 => 6, 2 => 10 );
    
    $resultyear = $selectbirthday[0];
    
    echo $resultyear;
    

    Thanks for the help! (thumbs up)

  • You sure know how to puzzle my mind! I'm glad it's solved :)

  • you could also do like so:

      <?php
      $ymd = array( 1946,6,10 );
      list( $year,$month,$day ) = $ymd;
      print "Year: $year";
    

    list() is underappreciated... : )