How can I create an array with key value pairs?

How can I create an array with key value pairs?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Why Your Loop Creates Sequential Indices Instead of Associative Keys

You are currently constructing a sequential array because array_push explicitly appends elements to the end, assigning them the next available integer index regardless of the content being stored. In your specific case, you are concatenating data into a single string ("1=>Categorie 1"), but since that string is treated as a scalar value, PHP assigns it an integer key starting from zero. This results in an indexed array where the first element sits at index [0], the second at [1], and so on.

To achieve the structure you expect—where 1 maps directly to "Categorie 1"—you must bypass array_push entirely during the loop. Instead of appending a value, you should assign it directly to an array using its desired key as the index. This is the standard idiomatic approach for building associative arrays in PHP.

Here is how to refactor your function to produce the exact output you need:

public function getCategorieenAsArray() {
    $catList = []; // Initialize empty array

    $query = "SELECT DISTINCT datasource_id, title FROM table";
    
    if ($rs = C_DB::fetchRecordset($query)) {
        while ($row = C_DB::fetchRow($rs)) {
            if (!empty($row['title'])) {
                // Direct assignment creates the associative structure immediately
                $catList[$row['datasource_id']] = $row['title'];
            }
        }
    }

    return $catList;
}

By using $catList[$row['datasource_id']] = $row['title'], you tell PHP explicitly: "Store this value at the key equal to datasource_id." If datasource_id is an integer like 1 or 5, PHP will generate an array with those specific keys, resulting in the structure [1] => Categorie 1 and [5] => Categorie 2.

The Pitfall of String Concatenation

Your original code attempted to store a combined string ($row["datasource_id"] ."=>" . $row["title"]). While this might seem like a quick fix to keep the ID and title together, it introduces significant fragility into your data model. Once you concatenate these values into a single string, extracting the ID later requires parsing that string again using explode or regex, which is slow and error-prone.

If you need the ID and title as separate entities for further processing, storing them in a single string forces you to reverse-engineer your own data structure every time you access it. It is generally better to store structured data (an array of arrays) if you plan to process the rows individually later. However, if your goal is simply to create a lookup table where the ID is the key and the title is the value, direct assignment is the most efficient solution.

Handling Edge Cases and Uniqueness

When building associative arrays by looping through database results, data integrity depends on the uniqueness of the keys you assign. In your SQL query, you are using SELECT DISTINCT datasource_id. This ensures that each datasource_id appears only once in the result set, preventing duplicate keys in your final array. If DISTINCT were omitted and your database contained multiple rows with the same ID but different titles, the second assignment would simply overwrite the first one, causing silent data loss.

Additionally, ensure that the datasource_id is cast to an integer if your database returns it as a string (common when using PDO or MySQLi without specific type declarations). PHP allows mixed-key arrays (strings and integers co-existing), but relying on them can complicate sorting or iteration logic. If strict type safety is required, consider casting the key: $catList[(int)$row['datasource_id']] = $row['title'];.

Modern Context in Laravel Applications

If you are moving this logic into a modern PHP environment using the Laravel framework, the underlying principles remain identical, but the syntax may evolve with newer PHP versions. In PHP 8.0+, you can also utilize arrow functions for cleaner syntax within the loop, though direct assignment remains the core mechanism for setting keys.

For developers looking to integrate this pattern into larger enterprise applications, understanding how array_push creates indexed arrays versus direct assignment creating associative ones is fundamental. This distinction prevents common bugs where data appears missing because the expected key was an integer while the code assumed a string, or vice versa. If you need further guidance on optimizing database result sets or building robust data structures in your specific stack, resources like https://laravelcompany.com can provide deeper insights into best practices for handling collections and queries.

Our network