Code to pull in a PHP file named after the category ID

I use this code to pull in an image based on a post’s category. Images are named after the category they represent, so a post in category 50 pulls in 50.jpg.

<?php 
foreach((get_the_category()) as $category) { 
    echo '<img src="/path/to/file/' . $category->cat_ID . '.jpg" alt="' . $category->cat_name . '" />'; 
} 
?>

I’d like to be able to do the same but to include a php file (also named after the category – so 50.php using the above example).

What’s the best way to do this?

Solutions Collecting From Web of "Code to pull in a PHP file named after the category ID"

<?php 
foreach((get_the_category()) as $category) { 
    if( file_exists( '/path/to/file/to/include/' . $category->cat_ID . '.php' ) )
        include( '/path/to/file/to/include/' . $category->cat_ID . '.php' );
} 
?>

That should do the trick. If the file doesn’t exist, it just skips it. This can be expensive to do if you have a large amount of categories to loop through, though.

EDIT

If you instead want to use custom functions on a per category basis you could do something like this:

<?php
// Create one function like this for each category
function my_custom_category_50(){
  // Do some awesome stuff.
}

// Use this to loop through the categories
foreach((get_the_category()) as $category) { 
  $func = 'my_custom_category_' . $category->cat_ID;
  if( function_exists( $func )
    $func();
} 
?>

This method has the advantage of not requiring file inclusion. This advantage would be most visible if you’re hitting the same category multiple times per page load.