arrays

What is the difference between array PUSH and POP? explain with example

In PHP, the array methods like array_push and array_pop are used to add or remove elements or items from the array. The array_push method can use to add or insert one or more items or elements from the end of an array. and The array_pop() method can use to extract, delete and remove the elements/items from the end of the array.

array_push() function

PHP array_push() is a built-in function used to insert new elements at the end of an array and get the updated array elements. The array_push() method takes a single element or an array of elements and appends it to the array.

Syntax:-

array_push(array,value1,value2...)

Parameters

An array parameter is required to which we will add the value.

The value1 parameter is also required, which is the value we will insert into the specified array.

The value2, value3, and so on are optional parameters. However, we need to pass those parameters if we want to add multiple values.

Example:-

<?php
    $nicname = ["Vijay", "Amit", "Dharmu"];

    array_push($nicname, "Ravi", "Rahul");

    echo "<pre>";
    print_r($nicname);
    echo "</pre>";
?>

Output:-

array_pop() function

PHP array_pop() function to remove an element or value from the end of an array. The array_pop() function also returns the last value of an array. However, if the array is empty (or the variable is not an array), the returned value will be NULL.

Syntax:-

array_pop(array);

Example:-

<?php
    $nicname = ["Vijay", "Amit", "Dharmu", "rahul"];

    array_pop($nicname);

    echo "<pre>";
    print_r($nicname);
    echo "</pre>";
?>

Output:-

How to emove duplicate values from PHP Array? explain with example

PHP array_unique

PHP array_unique() function to remove duplicate elements or values from an array. If the array contains the string keys, then this function will keep the first key encountered for every value, and ignore all the subsequent keys.

Example:-

<?php
   $array = array("a" => "One", "Tow", "One" => "Tow", "Three", "Four");
 
   // Deleting the duplicate items
   $result = array_unique($array);
   print_r($result);
?> 

Output:-

Removing duplicate values from an array in PHP

To remove duplicate values from an array in PHP, use the array_unique() function. If two or more array values are the same, the first appearance will be kept, and the other will be removed. The returned array will hold the first array item’s key type.

Syntax:-

array_unique(array, [sortingType])

Arguments

The array parameter is required, which specifies the array.

sortingType parameter is optional, and it specifies how to compare the array element. The following are some soringType flags.

  1. SORT_REGULAR – compare items usually (don’t change types)
  2. SORT_NUMERIC – compare items numerically
  3. SORT_STRING – compare items as strings
  4. SORT_LOCAL_STRING – compare items as strings based on the current locale.

Example:-

<?php

   $data = [20, 21, 21, 22, 21, 23, 22, 46, 47];

   print_r(array_unique($data));

?> 

Output:-

Associative Array in PHP array_unique() Function

Let’s pass the associative array to the array_unique function and see the output.

Example:-

<?php

    $data = ['a' => 'Vijay', 
        'b' => 'Amit',
        'd' => 'Vijay', 
        'f' => 'Amit', 
        'c' => 'Rahul', 
        'k' => 'Roshan', 
        'n' => 'Vijay'];
    $output = array_unique($data);
    print_r($output);

?> 

Output:-

Create a multidimensional array unique

You can create a multidimensional array unique for any single key index. 

Example:-

<?php

    function unique_multi_array($array, $key) { 
    $temp_array = array(); 
    $i = 0; 
    $key_array = array(); 
    
    foreach($array as $val) { 
        if (!in_array($val[$key], $key_array)) { 
            $key_array[$i] = $val[$key]; 
            $temp_array[$i] = $val; 
        } 
        $i++; 
    } 
    return $temp_array; 
  }
  
  $data = array( 
    0 => array("id"=>"1", "name"=>"Vijay",  "age"=>"26"), 
    1 => array("id"=>"2", "name"=>"Amit", "age"=>"25"), 
    2 => array("id"=>"1", "name"=>"Rahul",  "age"=>"26"), 
  ); 
  $output = unique_multi_array($data,'id');
  print_r($output);

?> 

Output:-

What is the difference between count or sizeof function in PHP? explain with example

According to PHP official documentation, there is no difference between count() or sizeof() function in PHP, which means both are the same, the sizeof() function is just the alias of count function i.e. the sizeof() uses the same as count function underneath. Both are used to count elements in an array.sizeof() function is an alias of count() function used in PHP. count() function is faster and butter than sizeof().

count() method: 

The count() method is used to calculate all the elements in the array or any other countable object. It can be used for both uni-dimensional as well as multi-dimensional arrays. 

count(array)

Example:-


<?php
        $parts = array(

                "Ram" => array(
                "SSD",
                "Processor"
            ),
                "Key" => array(
                "Monitor"  
            ),
                "Mouse" => array(
                "Cebal"
            )
        );
        
        print_r($parts);
        print("<br>");
        
        echo "Sub elements of an array: "
            . count($parts) . "<br>";
        echo "All elements of an array: "
            . count($parts, 1);
        
?>

Output:-

sizeof() method: 

The sizeof() method is used to calculate all the elements present in an array or any other countable object. It can be used for both uni-dimensional as well as multi-dimensional arrays. 

sizeof(arr, mode)

Example:-

<?php
    $parts = array(

        "Computer" => array(
        "SSD",
        "Processor"
    ),
        "Keyboard" => array(
        "Monitor"  
    ),
        "Mouse" => array(
        "CPU"
    )
);
    
    print_r($parts);
    print("<br>");
    
    echo "Sub elements of an array: "
        . sizeof($parts) . "<br>";
    echo "All elements of an array: "
        . sizeof($parts, 1);
 
?>

Output:-

Difference between sizeof() and count() methods:

  • The sizeof() method takes a longer execution time.
  • The sizeof() method is an alias of the count() method.
count() sizeof()
1. The count() returns the number of elements in the array.The sizeof() function is used to return the number of elements in an array.
2. Its syntax is -:
count(array, mode)
Its syntax is -:
sizeof(array, mode)
3. Its return value is of integer type.Its return value is of integer type.
4. The count() function may return 0 for a variable that is not set.This function is an alias of count() function.
5. It is supported in PHP version 4.0+It is supported in PHP version 4.0+

How to convert a JSON string to an array in PHP? explain with example

To convert the PHP array to JSON, use the json_encode() function. The json_encode() is a built-in PHP function that converts an array to json. The json_encode() function returns the string containing a JSON equivalent of the value passed to it, as demonstrated by the numerically indexed array. We can also convert any JSON received from a server into JavaScript objects.

Objects and arrays can be converted into JSON using the json_encode() method.

Example:-

<?php

    $netflix = ['Black Mirror', '13 Reasons Why', 'Bird Box', 'Dirt'];

    $netJSON = json_encode($netflix);

    echo $netJSON."\n";
    
?>

Output

A numerically indexed PHP array is translated to the array literal in a JSON string. JSON_FORCE_OBJECT option can be used if you want that array to be output as the object instead.

Convert Associative Array to JSON

Let’s take the example of converting a key-value pair array to json.

Example:-

<?php

    $data = ['name' => 'Vijay', 'blog' => 'AppDividend', 'education' => 'BE'];
    $jsonData = json_encode($data);
    echo $jsonData."\n";
    
?>

Output:-

List functions available to sort a php array? Explain with an Example.

PHP comes with a number of built-in functions designed specifically for sorting array elements in different ways like alphabetically or numerically in ascending or descending order. Here we’ll explore some of these functions most commonly used for sorting arrays.

Syntax:-

sort(array &$array, int $flags = SORT_REGULAR): bool

PHP array sort function examples

1) Using the PHP sort() function to sort an array of numbers

This example uses the PHP sort() function to sort an array of three numbers:

<?php

    $numbers = [2, 1, 3];
    sort($numbers);

    print_r ($numbers);
    
?>

Output:-

Array       
(
    [0] => 1
    [1] => 2
    [2] => 3
)

2) Using the PHP sort() function to sort an array of strings

This example uses the sort() function to sort an array of strings alphabetically:

<?php

    $names = ['Bob', 'John', 'Alice'];
    sort($names, SORT_STRING);

    print_r($names);
    
?>

Output:-

Array
(
    [0] => Alice
    [1] => Bob
    [2] => John
)

3) Using the PHP sort() function to sort an array of strings case-insensitively

<?php

    $fruits = ['apple', 'orange', 'banana', 'pink' ];
    sort($fruits);

    print_r($fruits);
    
?>

Output:-

4) Using the PHP sort() function to sort an array of strings using “natural ordering”

To sort an array of strings in the “natural ordering”, you combine the SORT_STRING  SORT_NATURAL flags.

Example:-

<?php

    $ranks = ['A-1', 'A-12', 'A-2',  'A-11'];
    sort($ranks, SORT_STRING | SORT_NATURAL);

    print_r($ranks);
    
?>

Output:-

How to Traverse an array in PHP and print?

The most common task with arrays is to do something with every element—for instance, sending mail to each element of an array of addresses, updating each file in an array of filenames, or adding up each element of an array of prices. There are several ways to traverse arrays in PHP, and the one you choose will depend on your data and the task you’re performing.

Example:-

<!DOCTYPE html>
<html>
	<body>
        <?php
            $array = array("Lux","Sampoo");

            foreach($array as $value) {
              print  " $value";
            }
        ?>
	</body>
</html>

Output:-

Lux Shampoo

Example:-

<!DOCTYPE html>
<html>
	<body>
        <?php
            $fnames = ["Amit", "Rahul", "Vijay", "Ravi", "Roshan"];

            $arrObject = new ArrayObject($fnames);
            $arrayIterator = $arrObject->getIterator();
                    
            while( $arrayIterator->valid() ){
                echo $arrayIterator->current() . "<br />";
                $arrayIterator->next();
            }
        ?>
	</body>
</html>

Output:-

What is Array in PHP? Write down the top 10 real use cases of Array in programming.

What is Array?

The array is a collection of items. The array is used for data types. The array is a special type of data structure that stores fixed-size data collection. We can store any amount of data in the array and use it easily. It also works like a database in which we can store the data. You can store it and use it. The array is a collection in which a lot of data can be stored. Array removes the complexity of the data. Many data problems can be removed by using PHP Array. The array() function is used to create an array. PHP array() function can contain (store, collect) many values.

Syntax of Array

array("value1", "value2 ", "value3");

In the above syntax, we have defined some values or items along with the array() function. PHP Array can also be defined as a database to store values. In the above syntax you can see value1, value2 and value3 in an array() function. These values(value1,value2,value3) can also be called item1,item2,item3 because array is a collection of similar items.

Examples of array

Example 1:-

<!DOCTYPE html>
<html>
  <body>
     <?php
       $fruits = array("Banana", "Mango ", "Orange");
       echo "I like " . $fruits[0] . ", " . $fruits[1] . " and " . $fruits[2] . ".";
?>
  </body>
</html>

Output

In the example above, we have created an array from a fruit variable. In Array, we have taken some items of fruits. The array contains index numbers. Index numbers start from 0 like – array(“Banana(0 index number )”, “Mango(1 index number ) “, “Orange(2 index number)”); Banana is stored at index number 0, Mango is stored at index number 1, and Orange is stored at index number 2.

Sometimes it goes out of our mind that array index numbers start from 0. If you think that array index numbers start with the number 1, then you are absolutely wrong. Keep in mind that Array index numbers start at 0. If an incorrect array index number is obtained, you will get an error or get another value. Array index numbers always start from 0.

We will also define the values one by one along with the index number of the array. This is another way to declare an array.

<?php 
   $x[0]=12;
   $x[1]=14;
   $x[2]=777;
   $x[3]=44;
?>
  <p>Sr No  
     <?php echo"$x[0]"; ?>
  </p>
  <p>Sr No 
     <?php echo "$x[1]"; ?>
  </p>
  <p>Sr No 
    <?php echo "$x[2]"; 
?>
  </p>
   Sr No <?php echo "$x[3]"; 
?>

Output:-

In the example above, we declared the array one after the other. $x is an array variable. In the first example, we used the variable once and we did not provide any type of index number, but in this example, we have defined different values with index numbers. So it is different from the first example.

Example 2:-

<?php 
   $odd_no= [1,3,5,7,9];
   $first_odd_number = $odd_no[0];
   $second_odd_number = $odd_no[1];
   $third_odd_number = $odd_no[2];
   $fourth_odd_number = $odd_no[3];

   echo "This is  first odd number = $first_odd_number";
   echo "<br>";
   echo "This is second odd number = $second_odd_number";
   echo "<br>";
   echo "This is  third odd number = $third_odd_number";
   echo "<br>";
   echo "This is fourth odd number = $fourth_odd_number";
?>

Output

This is first odd number = 1
This is second odd number = 3
This is third odd number = 5
This is fourth odd number = 7

Example 3:

<!DOCTYPE html>
<html>
	<body>
        <?php
            $age=array("Peter"=>"35","Ben"=>"37","Joe"=>"43");
            echo "Peter is " . $age['Peter'] . " years old.";
        ?>
	</body>
</html>

Output

Peter is 35 years old.

Example 4:

<!DOCTYPE html>
<html>
	<body>
        <?php
            $cars=array("Volvo","BMW","Toyota");
            $arrlength=count($cars);

            for($x=0;$x<$arrlength;$x++)
            {
                echo $cars[$x];
                echo "<br>";
            }
        ?>
	</body>
</html>

Output

Volvo
BMW
Toyota

Example 5:

<!DOCTYPE html>
<html>
	<body>
    <?php
        $age=array("Ram"=>"35","Lakshman"=>"37","Bharat"=>"43");

            foreach($age as $x=>$x_value)
        {
            echo "Key=" . $x . ", Value=" . $x_value;
            echo "<br>";
        }
?>
	</body>
</html>

Output

Key=Ram, Value=35
Key=Lakshman, Value=37
Key=Bharat, Value=43

Example 5:-

<!DOCTYPE html>
<html>
	<body>
        <?php
            $color1 = "Red";
            $color2 = "Green";
            $color3 = "Blue";

            echo $color1;
            echo "<br>";

            echo $color2;
            echo "<br>";

            echo $color3;
        ?>
	</body>
</html>

Output

Red
Green
Blue

Example 6:-

<!DOCTYPE html>
<html>
	<body>
        <?php
            $foo = array(1, 2, 3);
            $bar = ["A", true, 123 => 5]; 
            echo $bar[0]; 
            echo $bar[1]; 
            echo $bar[123]; 
        ?>
	</body>
</html>

Output

A15

<!DOCTYPE html>
<html>
	<body>
        <?php
          $arrays = [[1, 2], [3, 4], [5, 6]];

          foreach ($arrays as list($a, $b)) {
             $c = $a + $b;
             echo($c . ', '); 
          }
        ?>
	</body>
</html>

Output

3, 7, 11,

Example 6:-

<!DOCTYPE html>
<html>
	<body>
        <?php
            $names[0] = "Rajesh";
            $names[1] = "Rakesh";
            $names[2] = "Abhishekh";
            echo $names[1] . " and " . $names[2] . " are ". $names[0] . "'s neighbors";
        ?>
	</body>
</html>

Output

Rakesh and Abhishekh are Rajesh’s neighbors

Example 7:-

<!DOCTYPE html>
<html>
	<body>
        <?php
                $animals = array("Line"=>"Sher", "Cow"=>"Gai", "Tiger"=>"Bhag");

                // loop through associative array and get key-value pairs
                
                foreach($animals as $name => $value) {
                
                    echo "Name=" . $name . ", Value=" . $value;
                
                    echo "</br>";
                
                }
        ?>
	</body>
</html>

Outputs

Name=Line, Value=Sher
Name=Cow, Value=Gai
Name=Tiger, Value=Bhag

Example 8:-

<!DOCTYPE html>
<html>
	<body>
        <?php
            for ($row = 0; $row < 3; $row++) {

                echo "<p>Row number $row</p>";
              
                echo "<ul>";
              
            }
        ?>
	</body>
</html>

Outputs

Example 9:-

<!DOCTYPE html>
<html>
	<body>
        <?php
            $arr_variable = array (1,2,3,4,5);
  
            foreach( $arr_variable as $arritem )
            {
                echo "The array item is: $arritem <br />";
            }
  
        ?>
	</body>
</html>

Outputs

The array item is: 1
The array item is: 2
The array item is: 3
The array item is: 4
The array item is: 5

Example 10:-

<!DOCTYPE html>
<html>
	<body>
        <?php
            $arr = array(
                "Apple",
                "Banana",
                "Cherry"
            );
            $arrString = implode(" ", $arr);
            echo $arrString;
        ?>
	</body>
</html>

Outputs

Apple Banana Cherry

We have created an array that takes odd numbers. As you know, odd numbers start with 1,3,5,7,9. An odd number means, which cannot be completely divided by 2. An odd number is divisible by the same odd number. That is, 7 is divided by 7 and 3 by 3, after that, we stored different array values ​​in different variables, and after that, we displayed array values ​​one after the other with the help of the echo() function.