The following doesn't work after calling the $node->type. Can someone help?

$nid = 0;
$term_1 = "";

if (arg(0) == 'node' && is_numeric(arg(1))){ 
$nid = arg(1);

$node = node_load($nid);

if(true == strpos($node->type,'article'))
    $result = field_view_field('node', $node, 'field_tags_test', array('default'));
    $term_name = isset($result['#items'][0]['taxonomy_term']->name) ? $result['#items'][0]['taxonomy_term']->name : ""; 

If I take out the inner if-statement, then it works just fine.

Thanks for any help.

  • why you not write if ($node->type == 'article') ??? – Yusef Sep 5 '12 at 18:02
  • where you want put this code? why you are think so compelex? you can write this very simpler. – Yusef Sep 5 '12 at 18:06
  • zhilevan, this was in the page template. I originally had $node->type == 'article' but it wasn't working for some reason. I don't know if it's a bug in Drupal or something weird with PHP, but it turns out the error was due to having extra returns (e.g. right after the beginning <?php opening). – Nicole Sep 6 '12 at 13:50

strpos() returns the zero-based offset of the first occurrence of the test string. So if your string is article and the node type is article, it will return 0.

Your if statement is basically doing this check:

if (true == 0) { ...

Since 0 is a boolean FALSE in PHP the condition isn't satisfied, and the if construct is never entered.

There are a few ways you can change the if statement which basically boil down to the same thing:

  • if ($node->type == 'article') {
  • if (strpos($node->type, 'article') !== FALSE) {
  • if (strpos($node->type, 'article') === 0) {
  • Hi, thanks. I originally had the first one but it didn't work for some reason. Actually, after removing my if-statement and going back to the original code without it, the old code seemed to have stopped working too. I think I had an extra carriage return in there. I don't know why that would cause the problem?? – Nicole Sep 5 '12 at 18:08
  • Carriage returns wouldn't cause a problem unless they're in the middle of a line of code, I don't think that's the problem :) – Clive Sep 5 '12 at 18:14
  • I have no idea why it didn't work then. I double-checked everything and it wasn't in the middle of a piece of code. hmm...strange. Oh well, it works now after I removed extra returns! – Nicole Sep 6 '12 at 13:48

current strpos return 0 (this is FALSE)


true == strpos($node->type,'article'


$node->type == 'article'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.