Verification: a143cc29221c9be0

Php array with unique values

C++

#include

using namespace std;

int countDistinct(int arr[], int n)

{

    int res = 1;

    for (int i = 1; i

        int j = 0;

        for (j = 0; j

            if (arr[i] == arr[j])

                break;

        if (i == j)

            res++;

    }

    return res;

}

int main()

{

    int arr[] = { 12, 10, 9, 45, 2, 10, 10, 45 };

    int n = sizeof(arr) / sizeof(arr[0]);

    cout

    return 0;

}

Java

class GFG

{

static int countDistinct(int arr[], int n)

{

    int res = 1;

    for (int i = 1; i

    {

        int j = 0;

        for (j = 0; j

            if (arr[i] == arr[j])

                break;

        if (i == j)

            res++;

    }

    return res;

}

public static void main(String[] args)

{

    int arr[] = { 12, 10, 9, 45, 2, 10, 10, 45 };

    int n = arr.length;

    System.out.println(countDistinct(arr, n));

}

}

Python3

def countDistinct(arr, n):

    res = 1

    for i in range(1, n):

        j = 0

        for j in range(i):

            if (arr[i] == arr[j]):

                break

        if (i == j + 1):

            res += 1

    return res

arr = [12, 10, 9, 45, 2, 10, 10, 45]

n = len(arr)

print(countDistinct(arr, n))

C#

using System;

class GFG

{

static int countDistinct(int []arr, int n)

{

    int res = 1;

    for (int i = 1; i

    {

        int j = 0;

        for (j = 0; j

            if (arr[i] == arr[j])

                break;

        if (i == j)

            res++;

    }

    return res;

}

public static void Main()

{

    int []arr = { 12, 10, 9, 45,

                  2, 10, 10, 45 };

    int n = arr.Length;

    Console.WriteLine(countDistinct(arr, n));

}

}

PHP

function countDistinct( &$arr, $n)

{

    $res = 1;

    for ( $i = 1; $i $n; $i++)

    {

        for ($j = 0; $j $i; $j++)

            if ($arr[$i] == $arr[$j])

                break;

        if ($i == $j)

            $res++;

    }

    return $res;

}

$arr = array( 12, 10, 9, 45, 2, 10, 10, 45 );

$n = count($arr);

echo countDistinct($arr, $n);

?>

Javascript

function countDistinct(arr, n)

{

    let res = 1;

    for (let i = 1; i

        let j = 0;

        for (j = 0; j

            if (arr[i] === arr[j])

                break;

        if (i === j)

            res++;

    }

    return res;

}

    let arr = [ 12, 10, 9, 45, 2, 10, 10, 45 ];

    let n = arr.length;

    document.write(countDistinct(arr, n));

C++

#include

#include

using namespace std;

int countDistinct(int arr[], int n)

{

    sort(arr, arr + n);

    int res = 0;

    for (int i = 0; i

        while (i

            i++;

        res++;

    }

    return res;

}

int main()

{

    int arr[] = { 6, 10, 5, 4, 9, 120, 4, 6, 10 };

    int n = sizeof(arr) / sizeof(arr[0]);

    cout

    return 0;

}

Java

import java.util.Arrays;

class GFG

{

    static int countDistinct(int arr[], int n)

    {

        Arrays.sort(arr);

        int res = 0;

        for (int i = 0; i

        {

            while (i 1 &&

                    arr[i] == arr[i + 1])

            {

                i++;

            }

            res++;

        }

        return res;

    }

    public static void main(String[] args)

    {

        int arr[] = {6, 10, 5, 4, 9, 120, 4, 6, 10};

        int n = arr.length;

        System.out.println(countDistinct(arr, n));

    }

}

Python3

def countDistinct(arr, n):

    arr.sort();

    res = 0;

    i = 0;

    while(i

        while (i - 1 and

               arr[i] == arr[i + 1]):

            i += 1;

        res += 1;

        i += 1;

    return res;

arr = [ 6, 10, 5, 4, 9, 120, 4, 6, 10 ];

n = len(arr);

print(countDistinct(arr, n));

C#

using System;

class GFG

{

    static int countDistinct(int[] arr, int n)

    {

        Array.Sort(arr);

        int res = 0;

        for (int i = 0; i

        {

            while (i

                    arr[i] == arr[i + 1])

            {

                i++;

            }

            res++;

        }

        return res;

    }

    public static void Main()

    {

        int[] arr = {6, 10, 5, 4, 9, 120, 4, 6, 10};

        int n = arr.Length;

        Console.WriteLine(countDistinct(arr, n));

    }

}

PHP

function countDistinct($arr, $n)

{

    sort($arr, 0);

    $res = 0;

    for ($i = 0; $i $n; $i++)

    {

        while ($i $n - 1 &&

               $arr[$i] == $arr[$i + 1])

            $i++;

        $res++;

    }

    return $res;

}

$arr = array( 6, 10, 5, 4, 9, 120, 4, 6, 10 );

$n = sizeof($arr);

echo countDistinct($arr, $n);

?>

Javascript

function countDistinct(arr,n)

{

        arr.sort(function(a,b){return a-b;});

        let res = 0;

        for (let i = 0; i

        {

            while (i

                    arr[i] == arr[i + 1])

            {

                i++;

            }

            res++;

        }

        return res;

}

let arr=[6, 10, 5, 4, 9, 120, 4, 6, 10];

let n = arr.length;

document.write(countDistinct(arr, n));

C++

#include

using namespace std;

int countDistinct(int arr[], int n)

{

    unordered_setint> s;

    int res = 0;

    for (int i = 0; i

        if (s.find(arr[i]) == s.end()) {

            s.insert(arr[i]);

            res++;

        }

    }

    return res;

}

int main()

{

    int arr[] = { 6, 10, 5, 4, 9, 120, 4, 6, 10 };

    int n = sizeof(arr) / sizeof(arr[0]);

    cout

    return 0;

}

Java

import java.util.*;

class GFG

{

    public static int countDistinct(int arr[],int n)

    {

        HashSet hs = new HashSet();

        for(int i = 0; i

        {

            hs.add(arr[i]);

        }

        return hs.size();    

    }

    public static void main(String[] args)

    {

        int arr[] = new int[]{6, 10, 5, 4, 9,

                                120, 4, 6, 10};

        System.out.println(countDistinct(arr,

                                arr.length));

    }

}

Python3

def countDistinct(arr, n):

    s = set()

    res = 0

    for i in range(n):

        if (arr[i] not in s):

            s.add(arr[i])

            res += 1

    return res

arr = [6, 10, 5, 4, 9, 120, 4, 6, 10]

n = len(arr)

print(countDistinct(arr, n))

C#

using System;

using System.Collections.Generic;

class GFG

{

    public static int countDistinct(int []arr,int n)

    {

        HashSetint> hs = new HashSetint>();

        for(int i = 0; i

        {

            hs.Add(arr[i]);

        }

        return hs.Count;    

    }

    public static void Main()

    {

        int []arr = new int[]{6, 10, 5, 4, 9,

                                120, 4, 6, 10};

        Console.WriteLine(countDistinct(arr,

                                arr.Length));

    }

}

PHP

function countDistinct($arr, $n)

{

    $s = array();

    $res = 0;

    for ($i = 0; $i $n; $i++)

    {

        array_push($s,$arr[$i]);

    }

    $s = array_unique($s);

    return count($s);

}

$arr = array( 6, 10, 5, 4, 9, 120, 4, 6, 10 );

$n = count($arr);

echo countDistinct($arr, $n);

?>

What is a PHP Array?

A PHP array is a variable that stores more than one piece of related data in a single variable.

Think of an array as a box of chocolates with slots inside.

The box represents the array itself while the spaces containing chocolates represent the values stored in the arrays.

The diagram below illustrates the above syntax.
 

In this tutorial, you will learn-

  • Numeric Arrays
  • PHP Associative Array
  • PHP Multi-dimensional arrays
  • PHP Array operators

Numeric Arrays

Numeric arrays use number as access keys.

An access key is a reference to a memory slot in an array variable.

The access key is used whenever we want to read or assign a new value an array element.

Below is the syntax for creating numeric array in php. Array Example

Or

 value, …);
?>

HERE,

  • “$variable_name…” is the name of the variable
  • “[n]” is the access index number of the element
  • “value” is the value assigned to the array element.

Let’s now look at an example of a numeric array.

Suppose we have 5 movies that we want to store in array variables.

We can use the example shown below to do that.

Here,

Each movie is given an index number that is used to retrieve or modify its value. Observe the following code-

Output:

Once upon a time in China Eastern Condors

As you can see from the above examples, working with arrays in PHP when dealing with multiple values of the same nature is very easy and flexible.

Alternatively, the above array variables can also be created using the following code.

 "Shaolin Monk",
               1 => "Drunken Master",
               2 => "American Ninja",
               3 => "Once upon a time in China",
               4 =>"Replacement Killers" );
echo $movie[4];
?>

Output:

Replacement Killers

PHP Associative Array

Associative array differ from numeric array in the sense that associative arrays use descriptive names for id keys.

Below is the syntax for creating associative array in php.

 value);
?>

HERE,

  • “$variable_name…” is the name of the variable
  • “['key_name']” is the access index number of the element
  • “value” is the value assigned to the array element.

  Let’s suppose that we have a group of persons, and we want to assign the gender of each person against their names.

We can use an associative array to do that.The code below helps us to do that.

 "Female", "John" => "Male", "Mirriam" => "Female");
print_r($persons); 
echo ""; 
echo "Mary is a " . $persons["Mary"];
?>

 HERE,

Output:

Array ( [Mary] => Female [John] => Male [Mirriam] => Female ) Mary is a Female

Associative array are also very useful when retrieving data from the database.

The field names are used as id keys.

PHP Multi-dimensional arrays

These are arrays that contain other nested arrays.

The advantage of multidimensional arrays is that they allow us to group related data together.

Let’s now look at a practical example that implements a php multidimensional array.

The table below shows a list of movies by category.

Movie title Category
Pink Panther Comedy
John English Comedy
Die Hard Action
Expendables Action
The Lord of the rings Epic
Romeo and Juliet Romance
See no evil hear no evil Comedy

The above information can be represented as a multidimensional array. The code below shows the implementation.

 array("Pink Panther", "John English", "See no evil hear no evil"),
"action" => array("Die Hard", "Expendables"),
"epic" => array("The Lord of the rings"),
"Romance" => array("Romeo and Juliet")
);
print_r($movies);
?>

  HERE,

Output:

Array ( [comedy] => Array ( [0] => Pink Panther [1] => John English [2] => See no evil hear no evil ) [action] => Array ( [0] => Die Hard [1] => Expendables ) [epic] => Array ( [0] => The Lord of the rings ) [Romance] => Array ( [0] => Romeo and Juliet ) )

Another way to define the same array is as follows

 array(

                                0 => "Pink Panther",

                                1 => "john English",

                                2 => "See no evil hear no evil"

                                ),

                "action" => array (

                                0 => "Die Hard",

                                1 => "Expendables"

                                ),

                "epic" => array (

                                0 => "The Lord of the rings"

                                ),

                "Romance" => array

                                (

                                0 => "Romeo and Juliet"

                                )

);
echo $film["comedy"][0];
?>

Output:

Pink Panther

  Note: the movies numeric array has been nested inside the categories associative array

PHP Arrays: Operators

Operator Name Description How to do it Output
x + y Union Combines elements from both arrays
 1);

$y = array('value' => 10);

$z = $x + $y;
?>
Array([id] => 1 [value] => 10)
X == y Equal Compares two arrays if they are equal and returns true if yes.
 1);

$y = array("id" => "1");

if($x == $y)
{
echo "true";
}
else
{
echo "false";

}
?>
True or 1
X === y Identical Compares both the values and data types
 1);

$y = array("id" => "1");

if($x === $y)
{
echo "true";
}
else
{
echo "false";
}
?>
False or 0
X != y, x y Not equal  
 1);

$y = array("id" => "1");

if($x != $y)
{
echo "true";
}
else
{
echo "false";
}
?>
False or 0
X !== y Non identical  
 1);

$y = array("id" => "1");

if($x !== $y)
{
echo "true";
}
else
{
echo "false";
}
?>
True or 1

PHP Array Functions

Count function

The count function is used to count the number of elements that an php array contains. The code below shows the implementation.

Output:

3

is_array function

The is_array function is used to determine if a variable is an array or not. Let’s now look at an example that implements the is_array functions.

Output:

1

Sort

This function is used to sort arrays by the values.

If the values are alphanumeric, it sorts them in alphabetical order.

If the values are numeric, it sorts them in ascending order.

It removes the existing access keys and add new numeric keys.

The output of this function is a numeric array

 "Female", "John" => "Male", "Mirriam" => "Female");

sort($persons);

print_r($persons);
?>

Output:

Array ( [0] => Female [1] => Female [2] => Male )

ksort

This function is used to sort the array using the key. The following example illustrates its usage.

 "Female", "John" => "Male", "Mirriam" => "Female");

ksort($persons);

print_r($persons);
?>

Output:

Array ( [John] => Male [Mary] => Female [Mirriam] => Female )

asort

This function is used to sort the array using the values. The following example illustrates its usage.

 "Female", "John" => "Male", "Mirriam" => "Female");

asort($persons);

print_r($persons);

?>

Output:

Array ( [Mary] => Female [Mirriam] => Female [John] => Male )

Why use arrays?

  • Contents of Arrays can be stretched,
  • Arrays easily help group related information such as server login details together
  • Arrays help write cleaner code.

Remove Duplicate Values From An Array In PHP

In this example, we are taking a simple array as an example and the array_unique() method helps to remove the duplicate value in an array. so you can see the below example.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

$arr = array(1, 2, 2, 3, 4);

$final_arr = array_unique($arr);

echo "

"
;

print_r($final_arr);

echo "

";

//output

Array

(

    [0] => 1

    [1] => 2

    [3] => 3

    [4] => 4

)

?>

Remove duplicate values from associative array in PHP

In this example, we are taking an associative array as an example and the array_unique() method helps to remove the duplicate value in an array. here in this example car values are duplicates so the array_unique() method will remove the duplicate car value. so you can see the below example.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

$arr=array("a"=>"apple","b"=>"bike","c"=>"car","d"=>"dog","f"=>"car");

$final_arr = array_unique($arr);

echo "

"
;

print_r($final_arr);

echo "

";

//output

Array

(

    [a] => apple

    [b] => bike

    [c] => car

    [d] => dog

)

?>