Correct method of checking with an array has elements

I am trying to check a returned array exists before accessing its elements. At first I had

$img = wp_get_attachment_image_src($img_id, 'type')[0];

But since the array didn’t exist, I changed this to

Read More
$check = wp_get_attachment_image_src($img_id, 'type');
if ($check) {
    $img = wp_get_attachment_image_src($img_id, 'type')[0];
}

Despite this check (which is the same as the wordpress recommendation below) I still get the error within the if statement

Parse error: syntax error, unexpected ‘[‘

Here is the wordpress example usage below. I cannot see why mine is different. I have tried !empty($check) and a number of other things. What silly mistake am I making?

<?php 
$attachment_id = 8; // attachment ID

$image_attributes = wp_get_attachment_image_src( $attachment_id ); // returns an array
if( $image_attributes ) {
?> 
<img src="<?php echo $image_attributes[0]; ?>" width="<?php echo $image_attributes[1]; ?>" height="<?php echo $image_attributes[2]; ?>">
<?php } ?>

Related posts

Leave a Reply

2 comments

  1. you can’t append [] at the end of function calls for php version below 5.4. you first need to assign a variable to the function result.

    $check = wp_get_attachment_image_src($img_id, 'type');
    if ($check) {
        $img = $check[0];
    }