In array

Posted by Stephen thangaraj at 17:37
How To Join a List of Keys with a List of Values into an Array?
If you have a list keys and a list of values stored separately in two arrays, you can join them into a single array using the array_combine() function. It will make the values of the first array to be the keys of the resulting array, and the values of the second array to be the values of the resulting array. Here is a PHP script on how to use array_combine():
<?php
$old = array();
$old["Zero"] = "PHP";
$old[1] = "Perl";
$old["Two"] = "Java";
$old["3"] = "C+";
$old[""] = "Basic";
$old[] = "Pascal";
$old[] = "FORTRAN";
$keys = array_keys($old);
$values = array_values($old);
print("Combined:\n");
$new = array_combine($keys, $values);
print_r($new);
print("\n");
 
print("Combined backward:\n");
$new = array_combine($values, $keys);
print_r($new);
print("\n");
?>
This script will print:
Combined:
Array
(
    [Zero] => PHP
    [1] => Perl
    [Two] => Java
    [3] => C+
    [] => Basic
    [4] => Pascal
    [5] => FORTRAN
)
Combined backward:
Array
(
    [PHP] => Zero
    [Perl] => 1
    [Java] => Two
    [C+] => 3
    [Basic] =>
    [Pascal] => 4
    [FORTRAN] => 5
)
How To Merge Values of Two Arrays into a Single Array?
You can use the array_merge() function to merge two arrays into a single array. array_merge() appends all pairs of keys and values of the second array to the end of the first array. Here is a PHP script on how to use array_merge():
<?php
$lang = array("Perl", "PHP", "Java",);
$os = array("i"=>"Windows", "ii"=>"Unix", "iii"=>"Mac");
$mixed = array_merge($lang, $os);
print("Merged:\n");
print_r($mixed);
?>
This script will print:
Merged:
Array
(
    [0] => Perl
    [1] => PHP
    [2] => Java
    [i] => Windows
    [ii] => Unix
    [iii] => Mac
)
How To Use an Array as a Queue?
A queue is a simple data structure that manages data elements following the first-in-first-out rule. You use the following two functions together to use an array as a queue:
  • array_push($array, $value) - Pushes a new value to the end of an array. The value will be added with an integer key like $array[]=$value.
  • array_shift($array) - Remove the first value from the array and returns it. All integer keys will be reset sequentially starting from 0.
Here is a PHP script on how to use an array as a queue:
<?php
$waitingList = array();
array_push($waitingList, "Jeo");
array_push($waitingList, "Leo");
array_push($waitingList, "Kim");
$next = array_shift($waitingList);
array_push($waitingList, "Kia");
$next = array_shift($waitingList);
array_push($waitingList, "Sam");
print("Current waiting list:\n");
print_r($waitingList);
?>
This script will print:
Current waiting list:
Array
(
    [0] => Kim
    [1] => Kia
    [2] => Sam
)
How To Use an Array as a Stack?
A stack is a simple data structure that manages data elements following the first-in-last-out rule. You use the following two functions together to use an array as a stack:
  • array_push($array, $value) - Pushes a new value to the end of an array. The value will be added with an integer key like $array[]=$value.
  • array_pop($array) - Remove the last value from the array and returns it.
Here is a PHP script on how to use an array as a queue:
<?php
$waitingList = array();
array_push($waitingList, "Jeo");
array_push($waitingList, "Leo");
array_push($waitingList, "Kim");
$next = array_pop($waitingList);
array_push($waitingList, "Kia");
$next = array_pop($waitingList);
array_push($waitingList, "Sam");
print("Current waiting list:\n");
print_r($waitingList);
?>
This script will print:
Current waiting list:
Array
(
    [0] => Jeo
    [1] => Leo
    [2] => Sam
)
How To Randomly Retrieve a Value from an Array?
If you have a list of favorite greeting messages, and want to randomly select one of them to be used in an email, you can use the array_rand() function. Here is a PHP example script:
<?php
$array = array("Hello!", "Hi!", "Allo!", "Hallo!", "Coucou!");
$key = array_rand($array);
print("Random greeting: ".$array[$key]."\n");
?>
This script will print:
Random greeting: Coucou!
How To Loop through an Array without Using "foreach"?
PHP offers the following functions to allow you loop through an array without using the "foreach" statement:
  • reset($array) - Moves the array internal pointer to the first value of the array and returns that value.
  • end($array) - Moves the array internal pointer to the last value in the array and returns that value.
  • next($array) - Moves the array internal pointer to the next value in the array and returns that value.
  • prev($array) - Moves the array internal pointer to the previous value in the array and returns that value.
  • current($array) - Returns the value pointed by the array internal pointer.
  • key($array) - Returns the key pointed by the array internal pointer.
  • each($array) - Returns the key and the value pointed by the array internal pointer as an array and moves the pointer to the next value.
Here is a PHP script on how to loop through an array without using "foreach":
<?php
$array = array("Zero"=>"PHP", "One"=>"Perl", "Two"=>"Java");
print("Loop with each():\n");  
reset($array);
while (list($key, $value) = each($array)) {
  print("[$key] => $value\n");  
}
print("\n");  
 
print("Loop with current():\n");  
reset($array);
while ($value = current($array)) {
  print("$value\n");  
  next($array);
}
print("\n");  
?>
This script will print:
Loop with each():
[Zero] => PHP
[One] => Perl
[Two] => Java
 
Loop with current():
PHP
Perl
Java
How To Create an Array with a Sequence of Integers or Characters?
The quickest way to create an array with a sequence of integers or characters is to use the range() function. It returns an array with values starting with the first integer or character, and ending with the second integer or character. Here is a PHP script on how to use range():
<?php
print("Integers:\n");
$integers = range(1, 20, 3);
print_r($integers);
print("\n");
 
print("Characters:\n");
$characters = range("X", "c");
print_r($characters);
print("\n");
?>
This script will print:
Integers:
Array
(
    [0] => 1
    [1] => 4
    [2] => 7
    [3] => 10
    [4] => 13
    [5] => 16
    [6] => 19
)
 
Characters:
Array
(
    [0] => X
    [1] => Y
    [2] => Z
    [3] => [
    [4] => \
    [5] => ]
    [6] => ^
    [7] => _
    [8] => `
    [9] => a
    [10] => b
    [11] => c
)
Of course, you can create an array with a sequence of integers or characters using a loop. But range() is much easier and quicker to use.
How To Pad an Array with the Same Value Multiple Times?
If you want to add the same value multiple times to the end or beginning of an array, you can use the array_pad($array, $new_size, $value) function. If the second argument, $new_size, is positive, it will pad to the end of the array. If negative, it will pad to the beginning of the array. If the absolute value of $new_size if not greater than the current size of the array, no padding takes place. Here is a PHP script on how to use array_pad():
<?php
$array = array("Zero"=>"PHP", "One"=>"Perl", "Two"=>"Java");
$array = array_pad($array, 6, ">>");
$array = array_pad($array, -8, "---");
print("Padded:\n");
print(join(",", array_values($array)));
print("\n");
?>
This script will print:
Padded:
---,---,PHP,Perl,Java,>>,>>,>>
How To Truncate an Array?
If you want to remove a chunk of values from an array, you can use the array_splice($array, $offset, $length) function. $offset defines the starting position of the chunk to be removed. If $offset is positive, it is counted from the beginning of the array. If negative, it is counted from the end of the array. array_splice() also returns the removed chunk of values. Here is a PHP script on how to use array_splice():
<?php
$array = array("Zero"=>"PHP", "One"=>"Perl", "Two"=>"Java");
$removed = array_splice($array, -2, 2);
print("Remaining chunk:\n");
print_r($array);
print("\n");
print("Removed chunk:\n");
print_r($removed);
?>
This script will print:
Remaining chunk:
Array
(
    [Zero] => PHP
)
 
Removed chunk:
Array
(
    [One] => Perl
    [Two] => Java
)
How To Join Multiple Strings Stored in an Array into a Single String?
If you multiple strings stored in an array, you can join them together into a single string with a given delimiter by using the implode() function. Here is a PHP script on how to use implode():
<?php 
$date = array('01', '01', '2006');
$keys = array('php', 'string', 'function');
print("A formated date: ".implode("/",$date)."\n");
print("A keyword list: ".implode(", ",$keys)."\n");
?>
This script will print:
A formated date: 01/01/2006
A keyword list: php, string, function
How To Split a String into an Array of Substring?
There are two functions you can use to split a string into an Array of Substring:
  • explode(substring, string) - Splitting a string based on a substring. Faster than split().
  • split(pattern, string) - Splitting a string based on a regular expression pattern. Better than explode() in handling complex cases.
Both functions will use the given criteria, substring or pattern, to find the splitting points in the string, break the string into pieces at the splitting points, and return the pieces in an array. Here is a PHP script on how to use explode() and split():
<?php 
$list = explode("_","php_strting_function.html");
print("explode() returns:\n");
print_r($list);
$list = split("[_.]","php_strting_function.html");
print("split() returns:\n");
print_r($list);
?>
This script will print:
explode() returns:
Array
(
    [0] => php
    [1] => strting
    [2] => function.html
)
split() returns:
Array
(
    [0] => php
    [1] => strting
    [2] => function
    [3] => html
)
The output shows you the power of power of split() with a regular expression pattern as the splitting criteria. Pattern "[_.]" tells split() to split whenever there is a "_" or ".".
How To Get the Minimum or Maximum Value of an Array?
If you want to get the minimum or maximum value of an array, you can use the min() or max() function. Here is a PHP script on how to use min() and max():
<?php
$array = array(5, 7, 6, 2, 1, 3, 4, 2);
print("Minimum number: ".min($array)."\n");
print("Maximum number: ".max($array)."\n");
$array = array("Zero"=>"PHP", "One"=>"Perl", "Two"=>"Java");
print("Minimum string: ".min($array)."\n");
print("Maximum string: ".max($array)."\n");
?>
This script will print:
Minimum number: 1
Maximum number: 7
Minimum string: Java
Maximum string: Perl
As you can see, min() and max() work for string values too.
How To Define a User Function?
You can define a user function anywhere in a PHP script using the function statement like this: "function name() {...}". Here is a PHP script example on how to define a user function:
<?php 
function msg() {
  print("Hello world!\n");
}
msg(); 
?>
This script will print:
Hello world!
How To Invoke a User Function?
You can invoke a function by entering the function name followed by a pair of parentheses. If needed, function arguments can be specified as a list of expressions enclosed in parentheses. Here is a PHP script example on how to invoke a user function:
<?php 
function hello($f) {
  print("Hello $f!\n");
}
hello("Bob");
?>
This script will print:
Hello Bob!
How To Return a Value Back to the Function Caller?
You can return a value to the function caller by using the "return $value" statement. Execution control will be transferred to the caller immediately after the return statement. If there are other statements in the function after the return statement, they will not be executed. Here is a PHP script example on how to return values:
<?php 
function getYear() {
  $year = date("Y");
  return $year;
}
print("This year is: ".getYear()."\n");
?>
This script will print:
This year is: 2006
How To Pass an Argument to a Function?
To pass an argument to a function, you need to:
  • Add an argument definition in the function definition.
  • Add a value as an argument when invoking the function.
Here is a PHP script on how to use arguments in a function():
<?php 
function f2c($f) {
  return ($f - 32.0)/1.8;
}
print("Celsius: ".f2c(100.0)."\n");
print("Celsius: ".f2c(-40.0)."\n");
?>
This script will print:
Celsius: 37.777777777778
Celsius: -40
How Variables Are Passed Through Arguments?
Like more of other programming languages, variables are passed through arguments by values, not by references. That means when a variable is passed as an argument, a copy of the value will be passed into the function. Modipickzyng that copy inside the function will not impact the original copy. Here is a PHP script on passing variables by values:
<?php
function swap($a, $b) {
  $t = $a; 
  $a = $b;
  $b = $t;
}
$x = "PHP";
$y = "JSP";
print("Before swapping: $x, $y\n");
swap($x, $y);
print("After swapping: $x, $y\n");
?>
This script will print:
Before swapping: PHP, JSP
After swapping: PHP, JSP
As you can see, original variables were not affected.
How To Pass Variables By References?
You can pass a variable by reference to a function by taking the reference of the original variable, and passing that reference as the calling argument. Here is a PHP script on how to use pass variables by references:
<?php
function swap($a, $b) {
  $t = $a; 
  $a = $b;
  $b = $t;
}
$x = "PHP";
$y = "JSP";
print("Before swapping: $x, $y\n");
swap(&$x, &$y);
print("After swapping: $x, $y\n");
?>
This script will print:
Before swapping: PHP, JSP
After swapping: JSP, PHP
As you can see, the function modified the original variable.
Note that call-time pass-by-reference has been deprecated. You need to define arguments as references. See next tip for details.
Can You Define an Argument as a Reference Type?
You can define an argument as a reference type in the function definition. This will automatically convert the calling arguments into references. Here is a PHP script on how to define an argument as a reference type:
<?php
function ref_swap(&$a, &$b) {
  $t = $a; 
  $a = $b;
  $b = $t;
}
$x = "PHP";
$y = "JSP";
print("Before swapping: $x, $y\n");
ref_swap($x, $y);
print("After swapping: $x, $y\n");
?>
This script will print:
Before swapping: PHP, JSP
After swapping: JSP, PHP
Can You Pass an Array into a Function?
You can pass an array into a function in the same as a normal variable. No special syntax needed. Here is a PHP script on how to pass an array to a function:
<?php
function average($array) {
  $sum = array_sum($array);
  $count = count($array);
  return $sum/$count;
}
$numbers = array(5, 7, 6, 2, 1, 3, 4, 2);
print("Average: ".average($numbers)."\n");
?>
This script will print:
Average: 3.75
How Arrays Are Passed Through Arguments?
Like a normal variable, an array is passed through an argument by value, not by reference. That means when an array is passed as an argument, a copy of the array will be passed into the function. Modipickzyng that copy inside the function will not impact the original copy. Here is a PHP script on passing arrays by values:
<?php
function shrink($array) {
  array_splice($array,1);
}
$numbers = array(5, 7, 6, 2, 1, 3, 4, 2);
print("Before shrinking: ".join(",",$numbers)."\n");
shrink($numbers);
print("After shrinking: ".join(",",$numbers)."\n");
?>
This script will print:
Before shrinking: 5,7,6,2,1,3,4,2
After shrinking: 5,7,6,2,1,3,4,2
As you can see, original variables were not affected.
How To Pass Arrays By References?
Like normal variables, you can pass an array by reference into a function by taking a reference of the original array, and passing the reference to the function. Here is a PHP script on how to pass array as reference:
<?php 
function shrink($array) {
  array_splice($array,1);
}
$numbers = array(5, 7, 6, 2, 1, 3, 4, 2);
print("Before shrinking: ".join(",",$numbers)."\n");
shrink(&$numbers);
print("After shrinking: ".join(",",$numbers)."\n");
?>
This script will print:
Before shrinking: 5,7,6,2,1,3,4,2
After shrinking: 5
Note that call-time pass-by-reference has been deprecated. You need to define arguments as references. See next tip for details.
Can You Define an Array Argument as a Reference Type?
You can define an array argument as a reference type in the function definition. This will automatically convert the calling arguments into references. Here is a PHP script on how to define an array argument as a reference type:
<?php
function ref_shrink(&$array) {
  array_splice($array,1);
}
$numbers = array(5, 7, 6, 2, 1, 3, 4, 2);
print("Before shrinking: ".join(",",$numbers)."\n");
ref_shrink($numbers);
print("After shrinking: ".join(",",$numbers)."\n");
?>
This script will print:
BBefore shrinking: 5,7,6,2,1,3,4,2
After shrinking: 5
How To Return an Array from a Function?
You can return an array variable like a normal variable using the return statement. No special syntax needed. Here is a PHP script on how to return an array from a function:
<?php
function powerBall() {
  $array = array(rand(1,55), rand(1,55), rand(1,55), 
                 rand(1,55), rand(1,55), rand(1,42));
  return $array;    
}
$numbers = powerBall();
print("Lucky numbers: ".join(",",$numbers)."\n");
?>
This script will print:
Lucky numbers: 35,24,15,7,26,15
If you like those nummers, take them to buy a PowerBall ticket.


If you enjoyed this post and wish to be informed whenever a new post is published, then make sure you subscribe to my regular Email Updates. Subscribe Now!


Kindly Bookmark and Share it:

YOUR ADSENSE CODE GOES HERE

0 comments:

Have any question? Feel Free To Post Below:

 

© 2011. All Rights Reserved | Interview Questions | Template by Blogger Widgets

Home | About | Top