Showing posts with label array. Show all posts
Showing posts with label array. Show all posts

Friday, April 9, 2010

difference between ksort and asort in php

Interview Question:

What is the difference between ksort and asort in php?

Answer:

ksort - sorts an array by its key
asort - sorts an array by its value

Example.

<?php
$resource = array("d" => "answers", "a" => "php", "b" => "interview", "c" => "questions");
ksort($resource);
foreach ($resource as $key => $val) {
echo "$key = $val\n";
}
?>

The sample output is

a = php b = interview c = questions d = answers

asort arsort diffrerences

Question: what is the difference between asort and arsort?

Answer:

asort - sorts an array. It maintains index values.

arsort- It sorts an array in reverse manner.

Example for asort:


<?php
$fruits = array("d" => "php", "a" => "interview", "b" => "questions", "c" => "answers");
asort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>

The output is c = answers a = interview d = php b = questions

Example for arsort:

<?php
$fruits = array("d" => "php", "a" => "interview", "b" => "questions", "c" => "answers");
arsort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>

The output is

b = questions d = php a = interview c = answers

question about array sorts in php

Question: What are all the array sorts in php?

Answer: The following are the array sort functions

sort()
asort()
arsort()
krsort()
usort()
ksort()
natcasesort()
rsort()
shuffle()
array_multisort()
uasort()
uksort()
natsort()

Tuesday, April 6, 2010

What is array in php

Question: What is array in php and how to create an array in php?

Answer: In php array is an ordered map. It contains values and keys.

To create an array we need to use array keyword

Example:

$a= array('php','interview','questions','answers');

This creates simple array.