如何组合字符串用作php var?

While using Advanced Custom Fields for Wordpress I got to call some vars using get_field('my-custom-field');

I got this code which I would like to store in a function:

<img src="<?php the_sub_field('image-1'); ?>"> 
<?php $target_post = get_sub_field('target-1'); ?> 
<?php echo get_the_title($target_post); ?>

All I need to replace inside my function is the -1 to -2, -3, etc. How can I do this?

I have tried this, which does not work:

function imageBlock($fieldID = '1') {
   <img src="<?php the_sub_field('image-$fieldID'); ?>"> 
   <?php $target_post = get_sub_field('target-$fieldID'); ?> 
   <?php echo get_the_title($target_post); ?>
}

How can I pass the fieldID to the get_field('my-custom-field-1'); function?

You're trying to pass a variable into a single quoted string which will take the literal $ as part of the string, not the start of a variable. There are two ways to correct this.

Either with;

get_sub_field("target-$fieldID"); // double quotes

or

get_sub_field('target-' . $fieldID); // concat

So your function would be;

function imageBlock($fieldID = '1') {
    ?>
    <img src="<?php the_sub_field("image-$fieldID"); ?>"> 
    <?php $target_post = get_sub_field("target-$fieldID"); ?> 
    <?php
    echo get_the_title($target_post);
}

Having said that, I would split the logic out so that you were just returning the string of HTML like the other functions you're calling;

function imageBlock($fieldID = '1') {
    $sub_field = the_sub_field("image-$fieldID");
    $target_post = get_sub_field("target-$fieldID");
    $the_title = get_the_title($target_post);

    return "<img src=\"$sub_field\"> $the_title";
}

and you can echo the result, ie;

echo imageBlock(2);