What is switch statement in php ?
Switch is a conditional statement , which perform specific action according to various condition. It is equivalent to If else strcutures. Syntax :
[php]switch (variable) {
case label1:
This block will execute if variable=label1;
break;
case label2:
This block will execute if variable=label2;
break;
case label3:
This block will execute if variable=label3;
break;
default:
This block will execute if variable not matching with any label;
}
[/php]
variable can be integer,string, character, float, double etc..
switch is similar to if..elseif..esle statement.
Note : break is required , if you missed break then it will check next case and execute default case also.
<?php
$num = 2;
switch($num){
case 1:
echo "My number is One";
break;
case 2:
echo "My number is Two";
break;
case 3:
echo "My number is Three";
break;
default :
echo "Not matching";
}
?>
Output : My number is Two
1. Checking vowel & consonant(Only for Small case letter)
<?php
$c = 'u';
switch($c){
case 'a':
echo "$c is Vowel";
break;
case 'e':
echo "$c is Vowel";
break;
case 'i':
echo "$c is Vowel";
break;
case 'o':
echo "$c is Vowel";
break;
case 'u':
echo "$c is Vowel"; break;
default:
echo "$c is Consonant ";
}
?>
Output : u is Vowel
2. Wishing birthday on current date
<?php $dob = date("d/m");
switch($dob){ case "10/02":
echo "Happy birthday Somnath";
break;
case "23/07":
echo "Happy birthday Santosh";
break;
case "18/08":
echo "Happy birthday Anil";
break;
case "04/09":
echo "Happy birthday Jassi";
break;
case "11/12":
echo "Happy birthday Ritesh";
break;
default: echo "No birthday party";
} ?>
if Today's date is – 23/07/2011
Output : Happy birthday Santosh
1. Break keyword
The PHP break keyword is used to terminate the execution of a loop prematurely.
Once break statement executed , it immediately terminates the loop and no further iterations are made.
In the following example the condition test becomes true when the counter value reaches five:
Normalization Resolved Normalization is one of the favorite topics of interviewee. It does not matter whether you have mentioned DBMS in your resume or not .This question is going to come and the funny part is that all of us know
what is normalization?
What are the different types of normalization?
So when this question on being asked the interviewer who have already prepared for it start with the history of normalization and end with the geography of normalization but when the next question for which they have not prepared i.e. apply normalization in real case scenario.
Now here comes the real part of normalization and just because of not proper concepts, people end up confusing themselves. So the idea is to not only to get familiar with normalization but also how to apply it in real time scenario.
What is Normalization?
Database designed based on ER model may have some amount of inconsistency, ambiguity and redundancy. To resolve these issues some amount of refinement is required. This refinement process is called as Normalization. I know all of you are clear with the definition, let’s go with :
what is the need of normalization?
What are the problems we can face if we proceed without normalization?
What are the advantages of normalization?
Asking question to oneself is the best way to get familiar with all the concepts.
The need of Normalization
I am going to show you one simple E-R model database.
Student Details
Course Details
Result details
1001 Ram 11/09/1986
M4 Basic Maths 7
11/11/2004 89 A
1002 Shyam 12/08/1987
M4 Basic Maths 7
11/11/2004 78 B
1001 Ram 23/06/1987
H6 4
11/11/2004 87 A
1003 Sita 16/07/1985
C3 Basic Chemistry 11
11/11/2004 90 A
1004 Gita 24/09/1988
B3 8
11/11/2004 78 B
1002 Shyam 23/06/1988
P3 Basic Physics 13
11/11/2004 67 C
1005 Sunita 14/09/1987
P3 Basic Physics 13
11/11/2004 78 B
1003 Sita 23/10/1987
B4 5
11/11/2004 67 C
1005 Sunita 13/03/1990
H6 4
11/11/2004 56 D
1004 Gita 21/08/1987
M4 Basic Maths 7
11/11/2004 78 B
In first look the above table is looking so arranged and well in format but if we try to find out what exactly this table is saying to us , we can easily figure out the various anomalies in this table . Ok let me help you guys in finding out the same.
Insert Anomaly: We cannot insert prospective course which does not have any registered student or we cannot insert student details that is yet to register for any course.
Update Anomaly: if we want to update the course M4’s name we need to do this operation three times. Similarly we may have to update student 1003’s name twice if it changes.
Delete Anomaly: if we want to delete a course M4 , in addition to M4 occurs details , other critical details of student also will be deleted. This kind of deletion is harmful to business. Moreover, M4 appears thrice in above table and needs to be deleted thrice.
Duplicate Data: Course M4’s data is stored thrice and student 1002’s data stored twice .This redundancy will increase as the number of course offerings increases.
Process of normalization:
Before getting to know the normalization techniques in detail, let us define a few building blocks which are used to define normal form.
Determinant : Attribute X can be defined as determinant if it uniquely defines the value Y in a given relationship or entity .To qualify as determinant attribute need NOT be a key attribute .Usually dependency of attribute is represented as X->Y ,which means attribute X decides attribute Y.
Example: In RESULT relation, Marks attribute may decide the grade attribute .This is represented as Marks->grade and read as Marks decides Grade.
Marks -> Grade
In the result relation, Marks attribute is not a key attribute .Hence it can be concluded that key attributes are determinants but not all the determinants are key attributes.
Functional Dependency: Yes functional dependency has definition but let’s not care about that. Let’s try to understand the concept by example. Consider the following relation :
IName- Name of the instructor who delivered the course
Room#-Room number which is assigned to respective instructor
Marks- Scored in Course Course# by student Student #
Grade –Obtained by student Student# in course Course #
Student#,Course# together (called composite attribute) defines EXACTLY ONE value of marks .This can be symbolically represented as
Student#Course# Marks
This type of dependency is called functional dependency. In above example Marks is functionally dependent on Student#Course#.
Other Functional dependencies in above examples are:
Course# -> CourseName
Course#-> IName(Assuming one course is taught by one and only one instructor )
IName -> Room# (Assuming each instructor has his /her own and non shared room)
Marks ->Grade
Formally we can define functional dependency as: In a given relation R, X and Y are attributes. Attribute Y is functional dependent on attribute X if each value of X determines exactly one value of Y. This is represented as :
X->Y
However X may be composite in nature.
Full functional dependency: In above example Marks is fully functional dependent on student#Course# and not on the sub set of Student#Course# .This means marks cannot be determined either by student # or Course# alone .It can be determined by using Student# and Course# together. Hence Marks is fully functional dependent on student#course#.
CourseName is not fully functionally dependent on student#course# because one of the subset course# determines the course name and Student# does not having role in deciding Course name .Hence CourseName is not fully functional dependent on student #Course#.
Student#
Marks
Course#
Formal Definition of full functional dependency : In a given relation R ,X and Y are attributes. Y is fully functionally dependent on attribute X only if it is not functionally dependent on sub-set of X.However X may be composite in nature.
Partial Dependency: In the above relationship CourseName,IName,Room# are partially dependent on composite attribute Student#Course# because Course# alone can defines the coursename, IName,Room#.
Room#
IName
CourseName
Course#
Student#
Formal Definition of Partial dependency: In a given relation R, X and Y are attributes .Attribute Y is partially dependent on the attribute X only if it is dependent on subset attribute X .However X may be composite in nature.
Transitive Dependency: In above example , Room# depends on IName and in turn depends on Course# .Here Room# transitively depends on Course#.
IName
Room#
Course#
Similarly Grade depends on Marks,in turn Marks depends on Student#Course# hence Grade
Fully transitively depends on Student#Course#.
Key attributes : In a given relationship R ,if the attribute X uniquely defines all other attributes ,then the attribute X is a key attribute which is nothing but the candidate key.
Ex: Student#Course# together is a composite key attribute which determines all attributes in relationship REPORT(student#,Course#,CourseName,IName,Room#,Marks,Grade)uniquely.Hence Student# and Course# are key attributes.
Types of Normal Forms
First Normal Form(1NF)
A relation R is said to be in first normal form (1NF) if and only if all the attributes of the relation R are atomic in nature
Student Details
Course Details
Result details
1001 Ram 11/09/1986
M4 Basic Maths 7
11/11/2004 89 A
1002 Shyam 12/08/1987
M4 Basic Maths 7
11/11/2004 78 B
1001 Ram 23/06/1987
H6 4
11/11/2004 87 A
1003 Sita 16/07/1985
C3 Basic Chemistry 11
11/11/2004 90 A
1004 Gita 24/09/1988
B3 8
11/11/2004 78 B
1002 Shyam 23/06/1988
P3 Basic Physics 13
11/11/2004 67 C
1005 Sunita 14/09/1987
P3 Basic Physics 13
11/11/2004 78 B
1003 Sita 23/10/1987
B4 5
11/11/2004 67 C
1005 Sunita 13/03/1990
H6 4
11/11/2004 56 D
1004 Gita 21/08/1987
M4 Basic Maths 7
11/11/2004 78 B
Table shown above Student Details ,Course Details and Result Details can be further divided. Student Details attribute is divided into Student#(Student Number) , Student Name and date of birth. Course Details is divided into Course# ,Course Name,Prerequisites and duration. Similarly Results attribute is divided into DateOfexam,Marks and Grade.
Second Normal Form (2NF)
A relation is said to be in Second Normal Form if and only If :
It is in the first normal form ,and
No partial dependency exists between non-key attributes and key attributes.
Let us re-visit 1NF table structure.
Student# is key attribute for Student ,
Course# is key attribute for Course
Student#Course# together form the composite key attributes for result relationship.
Other attributes are non-key attributes.
To make this table 2NF compliant, we have to remove all the partial dependencies.
StudentName and DateOfBirth depends only on student#.
CourseName,PreRequisite and DurationInDays depends only on Course#
DateOfExam depends only on Course#.
To remove this partial dependency we need to split Student_Course_Result table into four separate tables ,STUDENT ,COURSE,RESULT and EXAM_DATE tables as shown in figure.
STUDENT TABLE
Student #
Student Name
DateofBirth
1001
Ram
Some value
1002
Shyam
Some value
1003
Sita
Some value
1004
Geeta
Some value
1005
Sunita
Some value
COURSE TABLE
Course#
CourseName
Duration of days
C3
Bio Chemistry
3
B3
Botany
8
P3
Nuclear Physics
1
M4
Applied Mathematics
4
H6
American History
5
B4
Zoology
9
RESULT TABLE
Student#
Course#
Marks
Grade
1001
M4
89
A
1002
M4
78
B
1001
H6
87
A
1003
C3
90
A
1004
B3
78
B
1002
P3
67
C
1005
P3
78
B
1003
B4
67
C
1005
H6
56
D
1004
M4
78
B
EXAM DATE Table
Course#
DateOfExam
M4
Some value
H6
Some value
C3
Some value
B3
Some value
P3
Some value
B4
Some value
In the first table (STUDENT) ,the key attribute is Student# and all other non-key attributes, StudentName and DateOfBirth are fully functionally dependant on the key attribute.
In the Second Table (COURSE) , Course# is the key attribute and all the non-key attributes, CourseName, DurationInDays are fully functional dependant on the key attribute.
In third table (RESULT) Student#Course# together are key attributes and all other non key attributes, Marks and Grade are fully functional dependant on the key attributes.
In the fourth Table (EXAM DATE) Course# is the key attribute and the non key attribute ,DateOfExam is fully functionally dependant on the key attribute.
At first look it appears like all our anomalies are taken away ! Now we are storing Student 1003 and M4 record only once. We can insert prospective students and courses at our will. We will update only once if we need to change any data in STUDENT,COURSE tables. We can get rid of any course or student details by deleting just one row.
Let us analyze the RESULT Table
Student#
Course#
Marks
Grade
1001
M4
89
A
1002
M4
78
B
1001
H6
87
A
1003
C3
90
A
1004
B3
78
B
1002
P3
67
C
1005
P3
78
B
1003
B4
67
C
1005
H6
56
D
1004
M4
78
B
We already concluded that :
All attributes are atomic in nature
No partial dependency exists between the key attributes and non-key attributes
RESULT table is in 2NF
Assume, at present, as per the university evaluation policy,
Students who score more than or equal to 80 marks are awarded with “A” grade
Students who score more than or equal to 70 marks up till 79 are awarded with “B” grade
Students who score more than or equal to 60 marks up till 69 are awarded with “C” grade
Students who score more than or equal to 50 marks up till 59 are awarded with “D” grade
The University management which is committed to improve the quality of education ,wants to change the existing grading system to a new grading system .In the present RESULT table structure ,
We don’t have an option to introduce new grades like A+ ,B- and E
We need to do multiple updates on the existing record to bring them to new grading definition
We will not be able to take away “D” grade if we want to.
2NF does not take care of all the anomalies and inconsistencies.
Third Normal Form (3NF)
A relation R is said to be in 3NF if and only if
It is in 2NF
No transitive dependency exists between non-key attributes and key attributes.
In the above RESULT table Student# and Course# are the key attributes. All other attributes, except grade are non-partially , non – transitively dependant on key attributes. The grade attribute is dependant on “Marks “ and in turn “Marks” is dependent on Student#Course#. To bring the table in 3NF we need to take off this transitive dependency.
Student#
Course#
Marks
1001
M4
89
1002
M4
78
1001
H6
87
1003
C3
90
1004
B3
78
1002
P3
67
1005
P3
78
1003
B4
67
1005
H6
56
1004
M4
78
UpperBound
LowerBound
Grade
100
95
A+
94
90
A
89
85
B+
84
80
B
79
75
B-
74
70
C
69
65
C-
After Normalizing tables to 3NF , we got rid of all the anomalies and inconsistencies. Now we can add new grade systems, update the existing one and delete the unwanted ones.
Hence the Third Normal form is the most optimal normal form and 99% of the databases which require efficiency in
Sorting an array and hash elements in Perl This is the answer to Ques# 17 (a) and 23 under Perl Basics in Perl Interview Questions
There are many situations when we need to display the data in sorted order. For example: Student details by name or by rank or by total marks etc. If you are working on data driven based projects then you will use sorting techniques very frequently.
In Perl we have sort function which sorts a list alphabetically by default. But there is not the end. We need to sort:
an array numerically or
case insensitive strings or
case sensitive strings
hash contents by keys or
hash contents by values or
reverse of all above said points
How sorting works in Perl
Sort subroutine has three syntaxes and last one is the most used syntax.
sort SUBNAME LIST
sort BLOCK LIST
sort LIST
In list context, it sorts the LIST and returns the sorted list value. In scalar context, the behavior of sort() is undefined.
If SUBNAME or BLOCK is omitted, sorts in standard string comparison order.
Standard string comparison means based on ASCII value of those characters. Like @arr = qw (Call all). In this case it will be sorted as Call all which was not expected. So to make it work properly we use case-insensitive sort.
If SUBNAME is specified, it gives the name of a subroutine that returns an integer less than, equal to, or greater than 0 , depending on how the elements of the list are to be ordered. (The <=> and cmp operators are extremely useful in such routines.)
Note: The values to be compared are always passed by reference and should not be modified . $a and $b are global variable and should not be declared as lexical variables.
sort() returns aliases into the original list like grep, map etc which should be usually avoided for better readability.
As sorting always does string sorting, so to do numeric sorting we need to use a special syntax which a sort {$a $b} LIST. We will see these conditions using Perl codes.
How reverse sorting works
Systax to use reverse sort is reverse LIST. It works on sorted LIST usually. But in scalar context, it concatenates the elements of LIST and returns a string value with all characters in the opposite order.
In scalar context if argument is not passed it will reverse the value of $_
Ex:
[perl]$_ = “dlrow ,olleH”;
print scalar reverse; #in this case print reverse would not works because it expects a LIST
[/perl]
How <=> and cmp work?
These are actually binary equality operator. Binary operator usually gives (0 or 1) or (true or false) but these gives three values based on the comparison result.
Binary “<=>” returns -1, 0, or 1 depending on whether the left argument is numerically less than, equal to, or greater than the right argument.
Binary “cmp” returns -1, 0, or 1 depending on whether the left argument is stringwise less than, equal to, or greater than the right argument.
Never mix string and numeric values in LIST else sorting result will be fearsome 🙁
Try this out:
[perl]
my @arr1 = qw(1 two 3 0 4 Two 5 six 7 8 9 ten);
my @arr2 = sort {$a cmp $b} @arr1;
print “\n@arr2\n”;
[/perl]
Let go through the codes for different scenarios: Example 1: Sorting an array of strings (case-sensitive and case-insensitive examples)
[perl]
#!/usr/bin/perl
use strict;
use warnings;
my @strarr = qw(two Two six Six alien Coders Alien coderS);
my @sorted = sort {$a cmp $b} @strarr; # same result as of sort @strarr
my @sortedcase = sort { uc $a cmp uc $b } @strarr; #case-insensitivie
print “\n@sorted\n@sortedcase\n”;
[/perl] Output:
Alien Coders Six Two alien coderS six two
alien Alien Coders coderS six Six two Two
Note: try to always use case insensitive for better string sorting results.
Example 2: Sorting an array of numbers
The Perl sort function sorts by strings instead of by numbers. If you do it in general way it would fetch unexpected result.
[perl] #!/usr/bin/perl
use strict;
use warnings;
my @sorted_numbers = sort @numbers;
print “@sorted_numbers\n”;
[/perl] The output you would see would be:
001 01 1 109 22 23 3 65 7 9
To sort numerically, declare your own sort block and use the binary equality operator i.e. flying saucer operator <=>:
[perl]
#!/usr/bin/perl
use strict;
use warnings;
my @sorted_numbers = sort {$a <=> $b} @numbers;
print “@sorted_numbers\n”;
[/perl] The output would now be:
1 01 001 3 7 9 22 23 65 109
Note that $a and $b do not need to be declared, even with use strict on, because they are special sorting variables.
Example 3: Sorting array backwards (for string and numbers)
To sort backwards you need to declare your own sort block, and simply put $b before $a. or use reverse keyword after simple sort.
For example, the standard sort is as follows:
[perl] #!/usr/bin/perl
use strict;
use warnings;
my @strings = qw(Jassi Alien Coders);
my @sorted_strings = sort @strings;
print “@sorted_strings\n”;
[/perl] The output would be:
Alien Coders Jassi
To do the same, but in reverse order:
[perl]
#!/usr/bin/perl
use strict;
use warnings;
my @strings = qw(Jassi Alien Coders);
my @sorted_strings = sort {$b cmp $a} @strings; # or reverse sort @strings
print “@sorted_strings\n”;
[/perl] The output is:
Jassi Coders Alien
And for numbers:
[perl]
#!/usr/bin/perl
use strict;
use warnings;
my @numbers = (23, 1, 22, 7, 109, 9, 65, 3);
my @sorted_numbers = sort {$b <=> $a} @numbers; # or reverse sort {$a $b} @numbers
print “@sorted_numbers\n”;
[/perl] The output is:
109 65 23 22 9 7 3 1
This was all about sorting array elements alphabetically or numerically. Now we will see how sorting works on hash elements.
Example 4: Sorting hashes by keys
You can use sort to order hashes. For example, if you had a hash as follows:
Suppose we want to display the members for each community sorted alphabetically or say by keys, then this code will do so:
[perl]
#!/usr/bin/perl
use strict;
use warnings;
If you want to sort the same hash by the values (i.e. the users beside each programming language), you could do the following:
[perl]
#!/usr/bin/perl
use strict;
use warnings;
my %members = (
C => 1,
Java => 7,
Perl => 12,
Linux => 3,
Hacking => 8,
);
# Using <=> instead of cmp because of the numbers
foreach my $language (sort {$members{$a} <=> $members{$b}} keys %members){
print $language . “: ” . $members{$language} . “\n”;
}
[/perl]
Output:
C: 1
Linux: 3
Java: 7
Hacking: 8
Perl: 12
Example: 5 Sorting complex data structures
We can also use sort function to sort complex data structures. For example, suppose we have an array of hashes (anonymous hashes) like:
[perl]
my @aliens = (
{ name => ‘Jassi’, age => 28},
{ name => ‘Somnath’, age => 27},
{ name => ‘Ritesh’, age => 24},
{ name => ‘Santosh’, age => 29},
{ name => ‘Ranjan’, age => 26},
{ name => ‘Kaushik’, age => 25},
);
[/perl]
And we wish to display the data about the people by name, in alphabetical order, we could do the following:
[perl]
#!/usr/bin/perl
use strict;
use warnings;
my @aliens = (
{ name => ‘Jassi’, age => 28},
{ name => ‘Somnath’, age => 27},
{ name => ‘Ritesh’, age => 24},
{ name => ‘Santosh’, age => 29},
{ name => ‘Ranjan’, age => 26},
{ name => ‘Kaushik’, age => 25},
);
foreach my $person (sort {$a->{name} cmp $b->{name}} @aliens) {
print $person->{name} . ” is ” . $person->{age} . “\n”;
}
[/perl] The output is:
Jassi is 28
Kaushik is 25
Ranjan is 26
Ritesh is 24
Santosh is 29
Somnath is 27
Sorting the same hash by age and using a subroutine (inline function)
Rather than writing the code inline, you can also pass in a subroutine name. The subroutine needs to return an integer less than, equal to, or greater than 0. Do not modify the $a and $b variables as they are passed in by reference, and modifying them will probably confuse your sorting.
[perl]
#!/usr/bin/perl
use strict;
use warnings;
my @aliens = (
{ name => ‘Jassi’, age => 28},
{ name => ‘Somnath’, age => 27},
{ name => ‘Ritesh’, age => 24},
{ name => ‘Santosh’, age => 29},
{ name => ‘Ranjan’, age => 26},
{ name => ‘Kaushik’, age => 25},
);
foreach my $person (sort agecomp @aliens) {
# it just replaced {$a->{age} <=> $b->{age}} by agecomp inline function
print $person->{name} . ” is ” . $person->{age} . ” years old\n”;
}
sub agecomp {
$a->{age} <=> $b->{age};
}
[/perl] The output would be:
Ritesh is 24 years old
Kaushik is 25 years old
Ranjan is 26 years old
Somnath is 27 years old
Jassi is 28 years old
Santosh is 29 years old
To find out more on sort function, run the command on Linux box:
perldoc -f sort
Visitor Rating: 5 Stars
Visitor Rating: 3 Stars