What's the syntax for doing a function to everything in an array?

Discussion in 'PHP' started by Polarbear4646, Jul 26, 2010.

  1. #1
    If this is possible please tell me how to do it, it's important.
     
    Polarbear4646, Jul 26, 2010 IP
  2. Deacalion

    Deacalion Peon

    Messages:
    438
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Deacalion, Jul 26, 2010 IP
  3. Polarbear4646

    Polarbear4646 Peon

    Messages:
    8
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    I'm trying to use the foreach loop, but I'm not sure how to do it and I didn't understand it from the link either.
     
    Polarbear4646, Jul 26, 2010 IP
  4. Deacalion

    Deacalion Peon

    Messages:
    438
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    0
    #4
    
    <?php
        // this array has 3 elements: one, two and three
        $myArray = array('one', 'two', 'three');
      
        // this will 'iterate' (repeat over) each element in the array
        foreach ($myArray as $element) {
            // so this is executed 3 times
            echo $element;
        }
    ?>
    
    PHP:
     
    Deacalion, Jul 26, 2010 IP
  5. Polarbear4646

    Polarbear4646 Peon

    Messages:
    8
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    I pretty much understand that, so I could replace echo with my function that I made and it would do that for each element of my array? Also, could element have been any name since it appears to be a variable?
     
    Polarbear4646, Jul 28, 2010 IP
  6. Polarbear4646

    Polarbear4646 Peon

    Messages:
    8
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #6
    Can I iterate through two arrays at the same time at the same speed? Or can I add to a variable inside the function every time it's iterated? Either one of these will work for me.
     
    Polarbear4646, Jul 28, 2010 IP
  7. ThePHPMaster

    ThePHPMaster Well-Known Member

    Messages:
    737
    Likes Received:
    52
    Best Answers:
    33
    Trophy Points:
    150
    #7
    As Deacalion said, the best approach is array_walk:

    
    $fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
    
    function test_print($item, $key)
    {
        echo "$key. $item<br />\n";
    }
    
    array_walk($fruits, 'test_print');
    
    PHP:
    You can see that array_talk will call the function test_print for every item in the array.
     
    ThePHPMaster, Jul 28, 2010 IP
  8. Polarbear4646

    Polarbear4646 Peon

    Messages:
    8
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #8
    Can someone explain that chunck of code? I don't understand what it does and does it do what I said I wanted it too?
     
    Polarbear4646, Jul 29, 2010 IP