如何根据对象值从选择中加载正确的数据

Before this gets marked as a duplicate know that the previous answers to older questions are not exactly the solution to this problem.

Here's the generic foreach loop:

<label>Type:</label>
<select name="postTypeArray">
  <?php foreach ($postTypeArray as $thePostType) : ?>
  <option value="<?php echo $thePostType ?>"><?php echo $thePostType ?></option>
  <?php endforeach; ?>
</select><br/><br/>

When the page loads the postType is either comment, image, or video. This is loaded from a database and stored in the postType object. The problem is when loading the page the selected postType is always comment which is the first value in the $postTypeArray, and when I use selected = "selected" the selected is always video which is the last value in the $postTypeArray.

I have tried if statements inside the foreach, used key value array, and etc. but have not found a solution yet.

Let's say you hold your values for the current item in $post['type'].

You then use a selected attribute to select the value.

<label>Type:</label>
<select name="postTypeArray">
<?php foreach ($postTypeArray as $thePostType) : ?>
  <option value="<?= $thePostType ?>"<?= (isset($post['type']) && $post['type'] === $thePostType ? ' selected' : '')?>><?= $thePostType ?></option>
<?php endforeach; ?>
</select>