use foreach data

Discussion in 'PHP' started by Fracisc, Sep 23, 2011.

  1. #1
    I have this:

    <?php 
    $titles[3] = 'three'; 
    $titles[2] = 'two'; 
    $titles[1] = 'one'; 
     
      
    foreach ($titles as $t ) { 
    print "title=$t "; 
    } 
     
    ?> 
    Code (markup):
    I don't want to print, I need to add all those values into a database, so I need all the values in a list, as a single variable. Something like
    $x="one, two, three";

    If I change the "print" with a "return" only the last array gets listed..

    Amy idea how to do what I need?
     
    Solved! View solution.
    Fracisc, Sep 23, 2011 IP
  2. TimK

    TimK Peon

    Messages:
    51
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #2
    
    <?php 
    $titles[3] = 'three'; 
    $titles[2] = 'two'; 
    $titles[1] = 'one'; 
     
      
    foreach ($titles as $t ) { 
    $result .= $titles[$t];
    } 
    
    echo($result);
    //To test to see if it is properly displayed. 
    ?>
    
    PHP:

    That should work. If not, let me know.
     
    TimK, Sep 23, 2011 IP
  3. Fracisc

    Fracisc Well-Known Member

    Messages:
    3,670
    Likes Received:
    10
    Best Answers:
    1
    Trophy Points:
    195
    #3
    That's what I thought too, but unfortunately it listed the latest one too..
     
    Fracisc, Sep 23, 2011 IP
  4. vidjin

    vidjin Peon

    Messages:
    6
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    You need to use Key Value method in your for each loop to provide a new index to the titles array everytime to get the next value.

    $result is declared before the loop so it can be used outside the loop as well.

    Please let us know if it works, works here with me. :)
     
    vidjin, Sep 24, 2011 IP
  5. #5
    Try this

    $titles[3] = 'three';
    $titles[2] = 'two';
    $titles[1] = 'one';
    
    
    $titles = array_reverse($titles, true);
    $s = implode(", ", $titles);
    echo $s;
    
    Code (markup):
     
    gvre, Sep 24, 2011 IP
  6. Fracisc

    Fracisc Well-Known Member

    Messages:
    3,670
    Likes Received:
    10
    Best Answers:
    1
    Trophy Points:
    195
    #6
    That worked. Thank you very much!
     
    Fracisc, Sep 24, 2011 IP