简体   繁体   中英

PHP: in_array not returning true

I have an issue with in_array not returning true even though duplicates are in an array. After doing some research on this site, I found that a lot of Windows users have issues due to invisible line breaks \\r\\n etc., but this seems to not be the case because after printing the length of each string, it matches with what I have (no invisible characters). Still, my code seems to be unable to match new values with what's already in the array:

$XMLName = "file.xml";
$XMLFile = simplexml_load_file($XMLName);

$categories = array();
$i = 0;

foreach($XMLFile as $ReadFile) {
    $cat = $ReadFile->CategoryName;

    $IsInArray = in_array($cat, $categories);

    if($IsInArray == FALSE) {
        $categories[$i] = $cat;
        $i++;
    }
}

foreach($categories as $category) {
    echo $category . "<br />";
}

Does anyone have a clue why this is the case?

try to replace line:

$cat = $ReadFile->CategoryName;

with this one:

$cat = trim($ReadFile->CategoryName->__toString());

and as @Jamil said you should better replace:

$categories[$i] = $cat; $i++;

with just

$categories[] = $cat;

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