Modify your first code chunk thusly:
$names = array();
$CatID = array( 1, 5, 3,);
foreach ( $CatID as $ID ) {
$names[] = get_the_category_by_ID( $ID );
// uncomment the next line to get the name tied to the ID
// $names[$ID] = get_the_category_by_ID( $ID );
}
var_dump( $names );
See PHP’s array()
reference for more info on using arrays.
Why your code isn’t working
In your first example, you’re looping through your $CatID
array, assigning the return from get_the_category_by_ID()
to $names
. Each time through the loop, you’re overwriting the $names
variable, which is why only 3
— the last one in your list — is sticking.
In your second example, you’re swinging too far the other way — you’re trying to get the value of $ID[$x]
, but $ID
isn’t an array, so you’re handing an invalid value (probably null
) to get_the_category_by_ID()
. That’s why it’s returning a passel of WP_Error
objects.