Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 9 of 10 · Arrays & String Functions
Interview question

How do you remove duplicate values from an array in PHP? PHP में array से duplicate values कैसे हटाएं?

Answer

Use array_unique() for simple scalar arrays, or a combination approach for arrays of associative sub-arrays where duplicates are defined by a specific field.

$nums = [1, 2, 2, 3, 3, 3];
$unique = array_unique($nums);
// [0 => 1, 1 => 2, 3 => 3]  -- note: keys are preserved, gaps remain
$reindexed = array_values($unique);
// [1, 2, 3]

For an array of associative arrays (e.g. removing duplicate users by email), array_unique() won't work directly since it compares whole (string-cast) values. Use array_column() plus array_unique() on the keys, or a manual loop:

$users = [
    ['id' => 1, 'email' => 'a@x.com'],
    ['id' => 2, 'email' => 'a@x.com'],
    ['id' => 3, 'email' => 'b@x.com'],
];
$unique = array_values(array_column($users, null, 'email'));
// keeps the last occurrence per unique email

Interview tip: Always mention that array_unique() preserves original keys, so pair it with array_values() if you need a clean sequential array afterward.

साधारण scalar arrays के लिए array_unique() इस्तेमाल करें, या associative sub-arrays वाले arrays के लिए जहाँ duplicates किसी specific field से तय होते हैं, combination approach अपनाएं।

$nums = [1, 2, 2, 3, 3, 3];
$unique = array_unique($nums);
// [0 => 1, 1 => 2, 3 => 3]  -- keys preserved, gaps रहते हैं
$reindexed = array_values($unique);
// [1, 2, 3]

associative arrays के array के लिए (जैसे email से duplicate users हटाना), array_unique() सीधे काम नहीं करेगा क्योंकि यह पूरी (string-cast) वैल्यू compare करता है। array_column() और array_unique() keys पर, या manual loop इस्तेमाल करें:

$users = [
    ['id' => 1, 'email' => 'a@x.com'],
    ['id' => 2, 'email' => 'a@x.com'],
    ['id' => 3, 'email' => 'b@x.com'],
];
$unique = array_values(array_column($users, null, 'email'));
// हर unique email का आखिरी occurrence रखता है

इंटरव्यू टिप: हमेशा बताएं array_unique() original keys preserve करता है, इसलिए साफ sequential array चाहिए तो array_values() के साथ इस्तेमाल करें।

Was this answer clear?