How put 'foreach' result to variable?

Discussion in 'PHP' started by Geepers, Apr 16, 2009.

  1. #1
    Hi there, I have a code, which checks for some value in an array

    foreach ($array as $val)
         if(isset($e->$val))   
     echo $e->$val; 
    PHP:
    How to put the results of this construction to a variable?
    For example: $а=$e->$val; - returns only the last result of the loop.
     
    Geepers, Apr 16, 2009 IP
  2. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #2
    If you only want the last value, just set the variable on each pass. In the end you will be left with the last variable.

    
    foreach ($array as $val):
    if(isset($e->$val)):
    $а=$e->$val;
    echo $e->$val;
    endif;
    endforeach;
    
    PHP:
     
    jestep, Apr 16, 2009 IP
  3. Geepers

    Geepers Peon

    Messages:
    5
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    sorry for misunderstanding, it returns several values and I need each of them in a variable. They'll go to a db after all.
     
    Geepers, Apr 16, 2009 IP
  4. austin-G

    austin-G Peon

    Messages:
    435
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Like this?


    $return = array();
    
    foreach ($array as $val)
         if(isset($e->$val))   
    $return[] = $e->$val; 
    PHP:
    And then you can run another foreach to do whatever you need to do with the data.
     
    austin-G, Apr 16, 2009 IP
    Geepers likes this.
  5. Geepers

    Geepers Peon

    Messages:
    5
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Thanks a lot, it works for me.
    Here is another question. How to get a part of string from start to some mark (for example a tag), then from another mark (end of the tag) to the end?:confused:
     
    Geepers, Apr 17, 2009 IP
  6. dumaas

    dumaas Peon

    Messages:
    22
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #6
    First find tag positions with strpos, and then use substr?
     
    dumaas, Apr 17, 2009 IP
  7. fourfingers

    fourfingers Peon

    Messages:
    37
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    0
    #7
    array_push($final_array,$e->$val) ;

    preg_match_all() + regex
     
    fourfingers, Apr 17, 2009 IP
  8. Geepers

    Geepers Peon

    Messages:
    5
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #8
    would you guys help me with the reg_exp?
    {Text A}<some_tag>Blah-blah</some_tag>{Text B}<some_tag>Blah-blah</some_tag>{Text C}
    HTML:
    I need {Text A},{Text B},{Text C}. And mind, that tags can be without closing tag.
    Thanks.
     
    Geepers, Apr 20, 2009 IP