How to save Asset field of an Entry programmatically in Craft 3 Using this answer on how to save data on Craft 3, I want to save also an asset field, but I cannot find out how.

It works for a Category field using the ids of the categories but not with ids of Assets.

Here is the code:

use craft\elements\Entry;
use craft\elements\MatrixBlock;

// Figure out the section &amp; entry type
$section = Craft::$app-&gt;sections-&gt;getSectionByHandle('news');
$entryTypes = $section-&gt;getEntryTypes();
$entryType = reset($entryTypes);

// Create an entry
$entry = new Entry([
    'sectionId' =&gt; $section-&gt;id,
    'typeId' =&gt; $entryType-&gt;id,
    'fieldLayoutId' =&gt; $entryType-&gt;fieldLayoutId,
    'authorId' =&gt; 1,
    'title' =&gt; 'My Entry',
    'slug' =&gt; 'my-entry',
    'postDate' =&gt; new DateTime(),
]);

// search categories and retrieve therir ids
$categorySlugs = ['cat1','cat2','cat3'];
$craftCategoryIds = [];
foreach ($categorySlugs as $cs) {
    $craftCategoryIds[] = Category::find()-&gt;wpSlug($cs)-&gt;one()-&gt;id;
}

// get a an asset to be used as a featureImage
$featureImageId = Asset::find()-&gt;myField('123')-&gt;one()-&gt;id;

// Set the custom field values (including Matrix)
$fieldValues = [
    'summary' =&gt; 'Some "summary" custom field value...',
    'categories' =&gt; $craftCategoryIds, // &lt;-- this works, categories are assigned
    'featuredImage' =&gt; $featureImageId, // &lt;-- doesn't work, featured image is not set
    'matrixField' =&gt; [
        'new1' =&gt; [
            'type' =&gt; 'blockTypeHandle',
            'fields' =&gt; [
                    // the block's custom field values...
            ],
        ],
        'new2' =&gt; [
            'type' =&gt; 'blockTypeHandle',
            'fields' =&gt; [
                    // the block's custom field values...
            ],
        ],
    ],
]);

$entry-&gt;setFieldValues($fieldValues)

// Save the entry
Craft::$app-&gt;elements-&gt;saveElement($entry);
That's because you have to insert an array of ids rather than a single id

$craftCategoryIds


is an array.

$featureImageId


is an integer. Even if you have just a single element you need to insert an array

'featuredImage' =&gt; [$featureImageId]


will work