Tag Archives: Array

call_user_func_array

call_user_func_array — Call a callback with an array of parameters

Calls the callback given by the first parameter with the parameters in param_arr.

Returns the return value of the callback, or FALSE on error.

<?php
 class Test {
 public function __call($name, $args){
 call_user_func_array(array('static', "test$name"), $args);
 }
 public function testS($l) {
 echo "$l,";
 }
 }
 
 class Test2 extends Test {
 public function testS($l) {
 echo "$l,$l,";
 }
 }
 
 
 $test = new Test2();
 $test->S('A');

?>

Arrays

• Way of ordering data by associating values to keys
• Unique keys are associated with a single value, or set of values
• Arrays can be nested, so that a value in one array actually represents a complete other array (multi-dimensional arrays)

Creating Arrays

INDEXED NUMERICALLY (INDEXED ARRAY)

o EX: $x = array(‘a’, ‘b’, ‘c’);
o EX: $x = [‘a’, ‘b’, ‘c’];
o EX: $x = array(0 => ‘a’, 1 => ‘b’, 2 => ‘c’);
o EX: $x = [0 => ‘a’, 1 => ‘b’, 2 => ‘c’];

INDEXED WITH STRINGS (ASSOCIATIVE ARRAY)

$x = array(
‘XML’ => ‘eXtensible Markup Language’
);
$x = [
‘XML’ => ‘eXtensible Markup Language’
];

Filling Arrays

• range() CREATES AN ARRAY WITH VALUES FROM AN INTERVAL

o DEFAULT STEP IS “1”

o EX: $x = range(1.2, 4.1) // == array(1.2, 2.2, 3.2)

usort

It sorts an array by keys using a user-defined comparison function

Example

<?php
function func($a, $b)
{
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
echo “<pre>”;
$array = array(1, 7, 5, 8, 4);
usort($array, “func”);
print_r($array);
?>

Output

Array
(
[0] => 1
[1] => 4
[2] => 5
[3] => 7
[4] => 8
)

uksort

It sorts an array by keys using a user-defined comparison function

Example

<?php
function func($a, $b)
{
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
echo “<pre>”;
$array = array(1=>”PHP”, 7=>”ASP”, 5=>”JS”, 8=>”AS”, 4=>”JSP”);
uksort($array, “func”);
print_r($array);
?>

Output

Array
(
[1] => PHP
[4] => JSP
[5] => JS
[7] => ASP
[8] => AS
)

uasort

It sorts an array with a user-defined comparison function and maintain index association

Example

<?php
echo “<pre>”;
$lan = array(“PHP”,”ASP”,”JSP”);
uasort($lan);
print_r($lan);
?>

Output

Array
(
[0] => PHP
[1] => ASP
[2] => JSP
)

rsort

It  sorts the array in reverse order

Example

<?php
echo “<pre>”;
$lan = array(“PHP”,”JSP”,”ASP”);
rsort($lan);
print_r($lan);
?>

Output

Array
(
[0] => PHP
[1] => JSP
[2] => ASP
)