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

Thread: multiply arrays

  1. #1
    New Coder
    Join Date
    Jan 2005
    Posts
    62
    Thanks
    1
    Thanked 0 Times in 0 Posts

    multiply arrays

    Hello, I have had no luck finding an answer to this question on either CodingForums or Google. All I want to do is multiply values from 2 arrays together. The first array contains a pricing list, the second array contains quantities entered by a user. The arrays are as follows:

    PHP Code:
        $prices = array(=> 35251030208605012554510503514403012202620);
    $quantity = array(=> $_SESSION['a2dfam'], $_SESSION['a2dinv'], $_SESSION['a2dstu'], $_SESSION['a1dfam'], $_SESSION['a1dinv'], $_SESSION['a1dstu'], $_SESSION['na2dfam'], $_SESSION['na2dinv'], $_SESSION['na2dstu'], $_SESSION['na1dfam'], $_SESSION['na1dinv'], $_SESSION['na1dstu'], $_SESSION['dec2dfam'], $_SESSION['dec2dinv'], $_SESSION['dec2dstu'], $_SESSION['dec1dfam'], $_SESSION['dec1dinv'], $_SESSION['dec1dstu'], $_SESSION['banquet'], $_SESSION['pizza'], $_SESSION['brunch'], $_SESSION['dues']); 
    I want to multiply each array value in $prices with the corresponding array value in $quantity in order to create a third array ($total). Also, if $quantity is not set, then I don't want to set the corresponding position in $total.

    The only option I've found is to use the array_walk function, but this doesn't seem ideal.

    Any advice?

    Ryan

  • #2
    Super Moderator Inigoesdr's Avatar
    Join Date
    Mar 2007
    Location
    Florida, USA
    Posts
    3,638
    Thanks
    2
    Thanked 404 Times in 396 Posts
    Remove the 1 => from the array and just loop over it:
    PHP Code:
    $total = array();
    for(
    $i 0$i count($quantity); $i++)
    {
        
    $total[] = $quantity[$i] * $prices[$i];

    This is just an example.

  • #3
    New Coder
    Join Date
    Jan 2005
    Posts
    62
    Thanks
    1
    Thanked 0 Times in 0 Posts
    No need to reply, it was too simple:

    PHP Code:
        for ($i=1$i<=22$i+=1) {
            
    $total[$i] = $prices[$i]*$quantity[$i];
        } 

  • #4
    New Coder
    Join Date
    Jan 2005
    Posts
    62
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Wow! Almost simultaneous replies! Thanks for the help.

    Ryan


  •  

    Posting Permissions

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