SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Addict
    Join Date
    Feb 2006
    Posts
    257
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Select values from array with highest value

    Hi,

    I have a bunch of arrays and need to select the one with the highest value for a certain position.

    For example, I have

    $array1[11]
    $array2[11]
    $array3[11]
    .... and so on for around 15 arrays. I have two variables that I need to fill with content from the array that has the highest [11] value as follows

    $var1 = $arrayX[11]
    $var2 = $arrayX[1]

    where X is the array with the highest value in [11].

    Does this make sense? If so, can anyone help me out?

    Thanks

  2. #2
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Since these 15 arrays all seem to be so related, you should consider making it into a single array with an additional depth.

    PHP Code:
    $big_array = array(
        
    $array1,
        
    $array2,
        
    $array3 //etc...
    );


    // we just assume for now the first one is the max
    $max_index $big_array[0][11];

    // here we find the real max
    foreach ($big_array as $index => $sub_array) {
        
    $max_index max($max_index$sub_array[11]);
    }

    echo 
    $max_index;
    echo 
    $big_array[$max_index][1]; 

  3. #3
    SitePoint Addict
    Join Date
    Feb 2006
    Posts
    257
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hi, thanks for the reply. I'm getting the following message when trying to use that exact code:

    Parse error: syntax error, unexpected T_VARIABLE, expecting ')' in /Applications/MAMP/htdocs/system/memodule.php on line 38762

    If I remove the code the page loads fine.

    Also, I'm not 100% sure I understand it - is $max_index that highest value from all of the [11]'s and $big_array[$max_index][1] the value from [1] for the array with the highest value of [11]?

    Thanks a lot.

  4. #4
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    There is no parse error in the code posted.

    But, after looking at what I posted, it wouldn't work right anyway.

    PHP Code:
    $big_array = array( 
        
    $array1
        
    $array2
        
    $array3 //etc... 
    ); 


    // we just assume for now the first one is the max 
    $max_index 0;
    $max_11 $big_array[0][11];

    // here we find the real max 
    foreach ($big_array as $index => $sub_array) { 
        if (
    $sub_array[11] > $max_11) {
            
    $max_index $index;
        }
    }

    echo 
    $max_index;
    echo 
    $big_array[$max_index][1]; 


Bookmarks

Posting Permissions

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