1

I'm using the following to get the raw value of a field Drupal:

$foo = field_get_items('node', $node, 'field_foo');
$foo_shift = array_shift($foo);
$foo_value = $foo_shift['value'];

Which works a treat but every so often I get the following error:

Warning: array_shift() expects parameter 1 to be array, boolean given in include() (line 106 of ).

I think it might have somehting to do with checking the value is set as I only get it after going to a page where the value isn't set. But if I try to check 'field_get_items('node', $node, 'field_foo')' is set that doesn't work.

2 Answers 2

1

How do you mean by "that doesn't work"? The problem is likely because field_get_items returns FALSE if the field doesn't exist on that node. Checking if $foo is empty (using empty) should work. So something like:

$foo = field_get_items('node', $node, 'field_foo');
if (!empty($foo)) {
  $foo_shift = array_shift($foo);
  $foo_value = $foo_shift['value'];
}

Alternately, because field_get_items returns false when it doesn't have a value to return, you could just put the $foo = ... line in the if statement itself:

if ($foo = field_get_items('node', $node, 'field_foo')) {
  $foo_shift = array_shift($foo);
  $foo_value = $foo_shift['value'];
}

The problem with isset is that it's just checking if the variable has a value attached to it. FALSE doesn't ping it as not being set, whereas FALSE is included in the list of values that are considered empty for empty.

The "Just to Remind" section of this posts: http://alexchernomaz.com/2014/10/14/php-empty-isset-is_null/ provides an excellent table of what values are considered empty/null/set for each function (empty, is_null, and isset), if you're interested in learning more.

1
  • Cool thanks that did the trick, used the second example, seemed the cleanest to me!
    – karl
    Nov 18, 2015 at 15:38
0

Never assume an array (or object) is filled. So after you retrieve an array or object (e.g. field_get_items) you always need to check if it has data before doing anything with that data.

In your case, your code would look something like this:

$foo = field_get_items('node', $node, 'field_foo');
if (!empty($foo)) {
  $foo_shift = array_shift($foo);
  $foo_value = $foo_shift['value'];
}

I mostly use the magical empty function which checks if the variable exists, is not empty, is not NULL and is not 0.

Edit: Erin was a sec faster posting the answer, at least we're on the same page. ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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