Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New Coder
    Join Date
    Aug 2006
    Posts
    44
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Multiply arrays?

    Can you multiply arrays in PHP?

    Like the array (1, 2, 3) multiplied by (10, 20) would create an array of all the possible results, i.e. an array of 6 items like (1*10, 1*20, 2*10, 2*20, 3*10, 3*20)?

    Sonja

  • #2
    New Coder
    Join Date
    Aug 2006
    Posts
    44
    Thanks
    4
    Thanked 0 Times in 0 Posts
    Is there a way of doing it with array_walk?

  • #3
    Regular Coder Zangeel's Avatar
    Join Date
    Oct 2007
    Location
    public_html/
    Posts
    638
    Thanks
    17
    Thanked 79 Times in 79 Posts
    Assuming youre example is exactly what you want:

    PHP Code:
    <?php
    $aNumbers 
    range(1,20); #Create array of 1 through 20

    print_r($aNumbers); #Show Array

    for ($i $i count($aNumbers) ; $i++)
    {
        
    $aMulti = (($i 2) == 1) ? 10 20 #If odd, 20, if even 10
        
    $aNumbers[$i] = $aNumbers[$i] * $aMulti#Multiplay the array pieces
    }

    print_r($aNumbers); #New Array
    ?>
    PHP Code:
    $aString is_string((string)array()) ? true false// true :D 
    [/CENTER]

  • Users who have thanked Zangeel for this post:

    Sonjaaa (09-15-2009)

  • #4
    Regular Coder funnymoney's Avatar
    Join Date
    Aug 2007
    Posts
    364
    Thanks
    17
    Thanked 24 Times in 24 Posts
    or like this..

    PHP Code:
    <?php
    $array_multiplicand 
    = array(1,2,3);
    $array_multiplier = array(10,20);

    $i=0;
    while(
    $i<count($array_multiplicand)) {
        foreach (
    $array_multiplier as $multiplier) {
         
    $array_product[] = $array_multiplicand[$i] * $multiplier;
        }
        
    $i++;
    }
    print_r($array_product);

    //outputs Array ( [0] => 10 [1] => 20 [2] => 20 [3] => 40 [4] => 30 [5] => 60 ) 
    ?>
    Last edited by funnymoney; 09-14-2009 at 10:52 AM. Reason: names...

  • Users who have thanked funnymoney for this post:

    Sonjaaa (09-15-2009)


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •