I need to get category titles for which I am using the a model where $result returns all the data from the categories table, what I need is only the titles, that by making a loop to $result and a comparison with in_array() I can obtain them.

$cat_ids = $params->get('catid'); // this is = array(2, 3, 4, 5, 7);
$categories = JModelLegacy::getInstance('Categories', 'ContentModel',array('ignore_request' => true));
$categories_items = $categories->getItems();
$category_titles = array();
foreach ($categories_items as $category) {
    if (in_array($category->id, $cat_ids)) {
        $category_titles[] = $category->title;
return $category_titles;

These titles can also be obtained by making a loop of $catids and in each iteration call to the database with $db = JFactory::getDbo();in this case if I need 5 titles I must make 5 queries to the database data.

$category_titles = array();
foreach ($cat_ids as $id) {
    $db = JFactory::getDbo();
    $query = $db->getQuery(true);
    $query->where($db->quoteName('id') . ' = ' . $db->quote($id));
    $category_titles[] = $db->loadResult();
return $category_titles;

My question: which is more efficient? do a query with lots of data or lots of queries with unique data?

Thanks. (I'm sorry for my English)

  • 2
    Can you post the queries you're planning to use? You should be able to get category titles with a single query using WHERE IN clause.
    – Sharky
    Apr 14, 2021 at 19:29
  • @Sharky Thanks for comment, I added full code of both options.
    – Leoalv
    Apr 14, 2021 at 20:15
  • @Leo your goal in terms of efficiency should always be to avoid iterated queries and more generally you should always endeavour to make as few trips to the database as possible. If you desire the result set to be in a particular order, you should use an ORDER BY clause as well. Apr 14, 2021 at 22:22


Browse other questions tagged or ask your own question.