Saturday, March 28, 2020

PHP Array

An array is a data structure that stores one or more similar type of values in a single value. The arrays are helpful to create a list of elements of similar types, which can be accessed using their index or key. 
Let's suppose you want to store colors in your PHP script. Storing the colors one by one in a variable could look something like this:
<?php  
 $color1 = "Red";  
 $color2 = "Green";  
 $color3 = "Blue";  
 ?> 
But what, if you want to store the states or city names of a country in variables and this time this not just three may be hundred. It is quite hard, boring, and bad idea to store each city name in a separate variable. And here array comes into play.

Advantage of PHP Array

  • Less Code: We don't need to define multiple variables.
  • Easy to traverse: By the help of single loop, we can traverse all the elements of an array.
  • Sorting: We can sort the elements of array.
     There are basically three types of arrays in PHP:
  • Indexed or Numeric Arrays: An array with a numeric index where values are stored linearly.
  • Associative Arrays: An array with a string index where instead of linear storage, each value can be assigned a specific key.
  • Multidimensional Arrays: An array which contains single or multiple array within it and can be accessed via multiple indices.

Indexed or Numeric Arrays
These types of arrays can be used to store any type of elements, but an index is always a number. By default, the index starts at zero. These arrays can be created in two different ways as shown in the following example:
<?php
 
// One way to create an indexed array
$name_one = array("Manish", "Sachin", "Ram", "Salim", "Raghav");
 
// Accessing the elements directly
echo "Accessing the 1st array elements directly:\n";
echo $name_one[2], "\n";
echo $name_one[0], "\n";
echo $name_one[4], "\n";
 
/* Second method to create array. */
$numbers[0] = "one";
$numbers[1] = "two";
$numbers[2] = "three";
$numbers[3] = "four";
$numbers[4] = "five";
        
// Looping through an array to access array elements using foreach
echo "Looping using foreach: \n";
 foreach( $numbers as $value ) {
echo "Value is $value <br />";
    }

// Looping through an array to access array elements using for
echo "\nLooping using for: \n";
for($i=0;$i<5;$i++)
echo $ numbers [$i]," ";


Associative Arrays
The associative arrays are very similar to numeric arrays in term of functionality but they are different in terms of their index. Associative array will have their index as string so that you can establish a strong association between key and values.
To store the salaries of employees in an array, a numerically indexed array would not be the best choice. Instead, we could use the employee's names as the keys in our associative array, and the value would be their respective salary.
NOTE − Don't keep associative array inside double quote while printing otherwise it would not return any value.

<?php
/* First method to associate create array. */
$salaries = array("Manish" => 2000, "Ramesh" => 1000, "zara" => 500);
       
echo "Salary of Manish is ". $salaries[Manish] . "<br />";
echo "Salary of Ramesh is ".  $salaries[Ramesh]. "<br />";
echo "Salary of zara is ".  $salaries['zara']. "<br />";
        
/* Second method to create array. */
$salaries[Manish] = "high";
$salaries[Ramesh] = "medium";
$salaries['zara'] = "low";

// Looping through an array using foreach       
echo "Looping using foreach: \n";
foreach ($salaries as $key => $val){
    echo "Salary of ".$key." is ".$val."\n";
}
?>

// Looping through an array using for
echo "\nLooping using for: \n";
$keys = array_keys($salaries);
$round = count($salaries); 
for($i=0; $i < $round; ++$i) {
    echo $keys[$i] . ' ' . $salaries [$keys[$i]] . "\n";
}


Multidimensional Arrays
Multi-dimensional arrays are such arrays that store another array at each index instead of a single element. In other words, we can define multi-dimensional arrays as an array of arrays. As the name suggests, every element in this array can be an array and they can also hold other sub-arrays within. Arrays or sub-arrays in multidimensional arrays can be accessed using multiple dimensions.
Example-1:
$emp = array  
  (  
  array(1,"sonoo",400000),  
  array(2,"john",500000),  
  array(3,"rahul",300000)  
  );  
  
for ($row = 0; $row < 3; $row++) {  
  for ($col = 0; $col < 3; $col++) {  
    echo $emp[$row][$col]."  ";  
  }  
echo "<br/>";  


Example-2:
<?php
         $marks = array(
            "Manish" => array (
               "physics" => 35,
               "maths" => 30,
               "chemistry" => 39
            ),
           
            "Ramesh" => array (
               "physics" => 30,
               "maths" => 32,
               "chemistry" => 29
            ),
           
            "zara" => array (
               "physics" => 31,
               "maths" => 22,
               "chemistry" => 39
            )
         );
        
         /* Accessing multi-dimensional array values */
         echo "Marks for Manish in physics : " ;
         echo $marks['Manish']['physics'] . "<br />";
        
         echo "Marks for Ramesh in maths : ";
         echo $marks['Ramesh']['maths'] . "<br />";
        
         echo "Marks for zara in chemistry : " ;
         echo $marks['zara']['chemistry'] . "<br />";
      ?>


PHP Array Functions

PHP provides various array functions to access and manipulate the elements of array. The important PHP array functions are given below.

1.     PHP array() function: PHP array() function creates and returns an array. It allows you to create indexed, associative and multidimensional arrays.

Example
<?php    
$season=array("summer","winter","spring","autumn");    
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";    
?>    
Output:
Season are: summer, winter, spring and autumn

2.     PHP array_chunk() function: PHP array_chunk() function splits array into chunks. By using array_chunk() method, you can divide array into many parts.

Example
<?php    
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");    
print_r(array_chunk($salary,2));   
?>    
Output:
Array ( 
[0] => Array ( [0] => 550000 [1] => 250000 ) 
[1] => Array ( [0] => 200000 )
)

3.     PHP count() function: PHP count() function counts all elements in an array.

Example
<?php    
$season=array("summer","winter","spring","autumn");    
echo count($season);    
?>    
Output:
4

4.     PHP sort() function: PHP sort() function sorts all the elements in an array.

Example
<?php    
$season=array("summer","winter","spring","autumn");    
sort($season);  
foreach$season as $s )    
{    
  echo "$s<br />";    
}    
?>    
Output:
autumn
spring
summer
winter

5.     PHP array_reverse() function: PHP array_reverse() function returns an array containing elements in reversed order.

Example
<?php    
$season=array("summer","winter","spring","autumn");    
$reverseseason=array_reverse($season);  
foreach$reverseseason as $s )    
{    
  echo "$s<br />";    
}    
?>    
Output:
autumn
spring
winter
summer

6.      PHP array_search() function: PHP array_search() function searches the specified value in an array. It returns key if search is successful.

Example
<?php    
$season=array("summer","winter","spring","autumn");    
$key=array_search("spring",$season);  
echo $key;    
?>    
Output:
2

7.     PHP array_intersect() function: PHP array_intersect() function returns the intersection of two array. In other words, it returns the matching elements of two array.

Example
<?php    
$name1=array("sonoo","john","vivek","smith");    
$name2=array("umesh","sonoo","kartik","smith");    
$name3=array_intersect($name1,$name2);  
foreach$name3 as $n )    
{    
  echo "$n<br />";    
}    
?>    
Output:
sonoo
smith

8.     Viewing Array Structure function: and Values: You can see the structure and values of an array by using one of two statements var_dump() or print_r(). The print_r() statement, however, it gives somewhat less information. Consider the following example:

Example
<?php
$cities = array("London", "Paris", "New York"); 
// Display the cities array
print_r($cities);
?>
Output:
Array ( [0] => London [1] => Paris [2] => New York )
This output shows the key and the value for each element in the array. To get more information, use the following statement:
Example
<?php
// Define array
$cities = array("London", "Paris", "New York"); 
// Display the cities array
var_dump($cities);
?>
Output:
array(3){[0]=>string(6) "London" [1]=>string(5) "Paris" [2]=>string(8) "NewYork"}

This output shows the data type of each element, such as a string of 6 characters, in addition to the key and value. 

PHP Array Sorting
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.
  • sort() and rsort() — For sorting indexed arrays
  • asort() and arsort() — For sorting associative arrays by value
  • ksort() and krsort() — For sorting associative arrays by key

Sorting Indexed Arrays in Ascending Order

The sort() function is used for sorting the elements of the indexed array in ascending order (alphabetically for letters and numerically for numbers).
Example:
<?php    
  // Define array    
  $colors = array("Red", "Green", "Blue", "Yellow");    
  // Sorting and printing array    
  sort($colors);    
  print_r($colors);   
  $numbers = array(1, 2, 2.5, 4, 7, 10);    
  sort($numbers);    
  print_r($numbers);   
 ?> 
 Output:
Array ( [0] => Blue [1] => Green [2] => Red [3] =>Yellow )
Array ( [0] => 1 [1] => 2 [2] => 2.5 [3] => 4 [4] => 7 [5] => 10 )

Sorting Indexed Arrays in Descending Order
The rsort() function is used for sorting the elements of the indexed array in descending order (alphabetically for letters and numerically for numbers).
Example:
<?php   
  $colors = array("Red", "Green", "Blue", "Yellow");   
  rsort($colors);   
  print_r($colors);   
  $numbers = array(1, 2, 2.5, 4, 7, 10);   
  rsort($numbers);   
  print_r($numbers);   
?>  
Output:
Array ( [0] => Yellow [1] => Red [2] => Green [3] => Blue )
Output:
Array ( [0] => 10 [1] => 7 [2] => 4 [3] => 2.5 [4]=> 2 [5] => 1 )

Sorting Associative Arrays in Ascending Order By Value
The asort() function sorts the elements of an associative array in ascending order according to the value. It works just like sort(), but it preserves the association between keys and its values while sorting.

Example
<?php   
  $age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);   
  // Sorting array by value and print   
  asort($age);   
  print_r($age);   
?> 
Output:
Array ( [Harry] => 14 [Peter] => 20 [Clark] => 35 [John] => 45 )

Sorting Associative Arrays in Descending Order By Value
The arsort() function sorts the elements of an associative array in descending order according to the value. It works just like rsort(), but it preserves the association between keys and its values while sorting.
Example
<?php
// Define array
$age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);
// Sorting array by value and print
arsort($age);
print_r($age);
?>
Output:
Array ( [John] => 45 [Clark] => 35 [Peter] => 20 [Harry] => 14 )

Sorting Associative Arrays in Ascending Order By Key

The ksort() function sorts the elements of an associative array in ascending order by their keys. It preserves the association between keys and its values while sorting, same as asort() function.
Example
<?php
// Define array
$age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);
// Sorting array by key and print
ksort($age);
print_r($age);
?>
Output:
Array ( [Clark] => 35 [Harry] => 14 [John] => 45 [Peter] => 20 ) 

Sorting Associative Arrays in Descending Order By Key

The krsort() function sorts the elements of an associative array in descending order by their keys. It preserves the association between keys and its values while sorting, same as arsort() function.
Example
<?php
// Define array
$age = array("Peter"=>20, "Harry"=>14, "John"=>45, "Clark"=>35);
// Sorting array by key and print
krsort($age);
print_r($age);
?>
Output:
Array ( [Peter] => 20 [John] => 45 [Harry] => 14 [Clark] => 35 )


Wednesday, March 25, 2020

Angular Service


Services in Angular are a great deal to share information among classes that do not know each other.  When we are developing the Angular app, we will most likely run into an outline in which we need to use the exact same code across multiple angular components. In that case, the Services will help us to get rid of that problem. We can share the services code among various angular components.
With Angular’s dependency injectionyou can inject the services around your app. 
Why we use Angular Service
There are many reasons why you would want to create and use the services in your Angular applications. One of the most common is the data service. The class that will handle getting and setting data from your datastore.
The data service that gets injected into each of those components allows you not to have to recreate the same datastore connection code in each component. Another common use of service is for some business logic.
The Angular framework has classes that are necessarily service classes. Things like HttpFormBuilder, and more, contain logic for doing specific things that are non-component specific. And again, through the dependency injection engine, you can get these services sent into your class constructors and use them.
Services in Angular provide an architectural way to encapsulate business logic in a reusable fashion, allowing you to keep that logic out of your components, directives, and pipe classes. This is not only beneficial for modularity, and single responsibility type of simplicity tier code, but it also makes the code more testable. 
If you employ a unit testing strategy, it becomes straightforward to mock the services that get used in a component. Thus your unit test can focus purely on confirming the behavior of the component and not its dependencies. 
Same goes for your services that get other services provided to them. So services, while not an enforced construct, are a fundamental building block to an Angular application.
In this case, Components use to display and present the data. Services use to fetch a data from an API. Let’s start our Angular Service Example. 
Angular 5 Service Example-1
Create a Service class: To create an angular service class, at the console, type the following command in your root of the folder.
ng g service services/myservice –flat true
create src\app\services\myservice.service.spec.ts
create src\app\services\myservice.service.ts
WARNING Service is generated but not provided, it must be provided to be used
It will create the following files.
  1. myservice.service.ts
  2. myservice.service.spec.ts

myservice.service.ts

import { Injectable } from '@angular/core';
@Injectable({
  providedIn: 'root'
})
export class MyServiceService {
  
  constructor() {}
}
Here, the Injectable module is imported from the @angular/core. It contains the @Injectable method and a class called MyserviceService. We will create our service function in this class.
Before creating a new service, we need to include the service created in the main parent app.module.ts.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { MyserviceService } from './services/service1.service';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent,
    CardserviceComponent,
    Card1Component,
    Card2Component,
    ServiceComponentComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    ReactiveFormsModule,
    RouterModule.forRoot(appRoutes)
  ],
  providers: [Service1ServiceMyserviceService],
  bootstrap: [AppComponent]
})
export class AppModule {}

We have imported the Service with the class name and the same class is used in the providers. Let us now switch back to the service class and create a service function.
In the service class, we will create a function that will display today’s date.  
Let us now see how the function looks in the service and how to use it in components.

import { Injectable } from '@angular/core';
@Injectable({
  providedIn: 'root'
})
export class MyserviceService {
  serviceproperty = 'Service Created and Injected';
  constructor() {}

  showTodayDate() {
    let ndate = new Date();
    return ndate;
  }
}

In the above service file, we have created a function showTodayDate. Now we will return the new Date () created.
Let us now see how to use the service in the new component created.

Service-Component.component.ts

import { ComponentOnInit } from '@angular/core';
import { MyserviceService } from '../services/myservice.service';

@Component({
  selector: 'app-service-component',
  templateUrl: './service-component.component.html',
  styleUrls: ['./service-component.component.css']
})
export class ServiceComponentComponent implements OnInit {
  todaydate;
  msg;
  constructor(private myserviceMyserviceService) {}

  ngOnInit() {
    this.todaydate = this.myservice.showTodayDate();
    this.msg = this.myservice.serviceproperty;
  }
}

The ngOnInit function gets called by default in any component created. The date is fetched from the service as shown above. To fetch more details of the service, we need to first include the service in the component .ts file.We will display the date in the Service-Component.component.html file as shown below –
<h2>
  {{ msg }}
</h2>
<h2>Today's Date : {{ todaydate }}</h2>

The selector of the new component is used in the app.component.html file. The contents from the above html file will be displayed in the browser as shown below –
Output (Service Example-1):


Global service vs. Local Service Injection in Angular 

( Dependency Injection )

To inject the service, you have the following two options.

1)     Inject as ‘global service.’

To inject as a global service, inject a service into the root module.
You need to register the module inside the app.module.ts file like we have done earlier in this post.
import { MyServiceService } from './services/Myservice.service'; 

@NgModule({ providers: [MyServiceService], })

2)     Inject as ‘local service’

To inject as local service, inject the service into component directly.
See the following code inside the Service-Component.component.ts file.

import { Component, OnInit } from '@angular/core';
import { MyServiceService } from '../services/Myservice.service'; 
 
@Component({
  selector: 'app-service-component',
  templateUrl: './ service-component.component.html',
  styleUrls: ['./ service-component.component.css'],
  providers: [MyServiceService]
})
export class ServiceComponentComponent implements OnInit{
  todaydate;
  msg;
 
  constructor(private myservice: MyserviceService){  }
  ngOnInit(){
     this.todaydate = this.myservice.showTodayDate();
     this.msg = this.myservice.serviceproperty;   
  }
}

So, we can register the service in Angular, either locally or globally.
If you are using services on more than one component, then you should define one global, and otherwise, local works just fine. It depends on the size of the project.