JanisOzolins JanisOzolins - 5 months ago 13
PHP Question

Cannot compare two identical strings in PHP?

I've been stuck for 6 hours on this one piece of code. What am I doing wrong?

I cannot seem to be able to compare the value of two strings the_title() and either just normal string directly in the IF statement or the same string from a different variable. That IF statement just doesn't work. I tried both with ==, === and with strcmp() but nothing, it just refuses to admit that both strings are indeed identical (I've printed them out several times and they match). Any thoughts?

<?php

$args = array( 'post_type' => 'team', 'showposts' => -1 );

$items = new WP_Query( $args );

while ($items->have_posts()) : $items->the_post();
$title = the_title(); // one of the titles in the while loop is indeed "Jon Snow"
$comp = 'Jon Snow';

if ( $title === $comp ){
echo 'Success!';
}
endwhile;
wp_reset_query();
?>


Oh and every time IF statement doesn't work, the system just prints out all the the_title() values in the while loop.

Answer

Oh and every time IF statement doesn't work, the system just prints out all the the_title() values in the while loop.

You've answer in your own question. the_title() by default prints the title of the post. To compare the title your first have to save it in variable and then compare.

the_title() accepts 3 parameters and 3rd parameter(FALSE) is to get the title as return value instead of just printing it. 3rd parameter is TRUE by default and it prints the title on page.

This is how you can do it.

<?php $posttitle=the_title( '', '', FALSE); ?>
Comments