How to remove duplicates elements from an array in PHP?

  • Posted on December 9, 2024
  • Technology
  • By MmantraTech
  • 45 Views
1a894a40-7248-426c-ac1b-0e37a39fd7da-3zId06UmDA.webp

Solution : Without using pre-built method

 

<?php


$array = [1, 2, 2, 3, 4, 4, 5];

    $unique_array = []; 
    
    foreach ($array as $value) {
        if (!isset($unique[$value])) { // Check if the value is already in the unique array
            $unique[$value] = $value; // Mark the value as seen
        }
    }

    $res = array_keys($unique);
    print_r($res);




?>

 

Solution : Using pre-built method

<?php
// Example array with duplicates
$array = [1, 2, 2, 3, 4, 4, 5];

// Remove duplicates
$uniqueArray = array_unique($array);

// Output the result
print_r($uniqueArray);
?>
1
Author
No Image
Admin
MmantraTech

Mmantra Tech is a online platform that provides knowledge (in the form of blog and articles) into a wide range of subjects .

You May Also Like

Write a Response