简体   繁体   中英

Max() returning second highest number…?

In my code below, print_r($vu_array) returns:

Array ( [0] => 249.99 [1] => 10.99 [2] => 29.99 [3] => 11.99 [4] => 10.99 )

but max($vu_array) returns 29.99 and NOT 249.99! What evil sorcery is going on here....?

    $vu_link = get_field('shop_link');

    $ch3 = curl_init($vu_link);
    curl_setopt($ch3, CURLOPT_RETURNTRANSFER, true);
    $cl3 = curl_exec($ch3);

    $dom3 = new DOMDocument();
    @$dom3->loadHTML($cl3);
    $xpath3 = new DOMXpath($dom3);

    $price3 = $xpath3->query("//p[@class='special-price']/span[@class='price']");

    foreach($price3 as $value) {
      $vu_array[] =  str_replace('$', '', $value->nodeValue);
    }

EDIT:

var_dump($vu_array) returns:

array(5) { [0]=> string(43) " 249.99 " [1]=> string(42) " 10.99 " [2]=> string(42) " 29.99 " [3]=> string(42) " 11.99 " [4]=> string(42) " 10.99 " } 

You are doing lexical (string) comparisons. Try changing the line inside your loop to:

$vu_array[] = floatval(str_replace('$', '', $value->nodeValue));

You have spaces in your array, so this should work:

<?php

    $vu_array = array(" 249.99 ", " 10.99 ", " 29.99 ", " 11.99 ", " 10.99 ");
    $vu_array = array_map("trim", $vu_array);
    echo max($vu_array);

?>

Output:

249.99

Your input array is holding string values . If you want the max() function to work correctly your array should contain float -values.

Here I made a small example code of how to get the max-value by your given input array.

$string_arr = array( ' 249.99 ', ' 10.99 ', ' 29.99 ', ' 11.99 ', ' 10.99 ' );

$int_arr = array_map('floatval', $string_arr ); //converts all values from string to float

$biggest = max( $int_arr );

var_dump($biggest); //outputs 249.99

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM