Skip to content
PHP Logo

How can one create an array with unique keys and values when retrieving data from a database in PHP?

When retrieving data from a database in PHP, you may encounter duplicate keys or values in the result set, especially if the data is not distinct in the database. To create an array with unique keys and values, you can use the `array_unique()` function in PHP. This function removes duplicate values from an array, ensuring that each key and value is unique.

php
// Retrieve data from the database
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);

// Create an empty array to store unique key-value pairs
$uniqueArray = array();

// Loop through the result set and add unique key-value pairs to the array
while ($row = mysqli_fetch_assoc($result)) {
    $uniqueArray[$row['unique_key']] = $row['unique_value'];
}

// Remove any duplicate values from the array
$uniqueArray = array_unique($uniqueArray);

// Print the array with unique keys and values
print_r($uniqueArray);