无法比较PHP中IF语句中的两个字符串


Unable to compare two strings in IF statement in PHP

好吧,所以我一直在尝试为一个web应用程序构建服务器端,该应用程序需要从两个XML文件中获取信息并对它们进行比较,一次一个元素。出于某种原因,我的代码将执行除比较这两个节点之外的所有操作。

代码:

function getCoursesByRole($role){
    s("role is ". $role);
    $xml = getxml(); # get the XML file
    $roles = getRoles();#load the roles file
    $modules = array();
    foreach($roles->children() as $project){
    s($project->name);
        if($project->name == $role){
            s("found:". $role);
            $courses = $project->courses->children();
            #echo "courses   ". $courses;
            foreach($courses as $theCourse){
                foreach($xml->children() as $course){
                    s("looking for $theCourse.... found ".$course->name);
                    if($theCourse == $course->name){
                        s("found $theCourse");
                        array_push($modules, array('name' => $course->name));
                        break;
                    }
                }
            }
        }
    }
    #echo array_values($modules);
    return $modules;
}

从输出来看,我认为问题是一个逻辑问题。

role is core
core
found:core
looking for Fire Safety.... found Administration of Medication
looking for Fire Safety.... found An Introduction to GIRFEC
looking for Fire Safety.... found Equality and Diversity
looking for Fire Safety.... found Fire Safety
looking for Fire Safety.... found Food Safety
looking for Fire Safety.... found Infection Control
looking for Fire Safety.... found Introduction to Health and Safety
looking for Fire Safety.... found Introduction to Safer Handling
looking for Fire Safety.... found Managing Volunteers
looking for Fire Safety.... found QStar

我只展示了s("looking for $theCourse.... found ".$course->name);的一次迭代,它得到了相当长的

如果有人能看到解决方案,我将不胜感激:)

当使用if(trim($a)==trim($b))作为条件时,用trim()函数修剪字符串总是个好主意。-海上

这条评论回答了我的问题。将这一行:if($theCourse == $course->name){改为这一行if(trim($theCourse) == trim($course->name)){后,代码工作得很好。