How can I get a list of custom post IDs into a variable I can use for another function?

You can push all your individual id’s from your foreach loop to a variable outside your foreach loop, like this (please note, this is not the preferred method as there is a simpler method, just scroll down)

$post_ids = [];
foreach((array) $all_posts->posts as $id) {
   $post_ids[] = $id;
}
?><pre><?php var_dump($post_ids); ?></pre><?php 

$post_ids will hold your array of id’s

Alternatively, which is actually the better and preferred method here, $all_posts->posts already holds an array of post ids, just assign that to a variable

$post_ids = $all_posts->posts; 
?><pre><?php var_dump($post_ids ); ?></pre><?php    

EDIT

If you need a string of id’s, you can just implode $post_ids

$string_ids = implode( ',', $post_ids );