function foo($first, ...$other) {
var\_dump($first); # => a
var\_dump($other); # => ['b', 'c']
}
foo('a', 'b', 'c' /\*, ...\*/ );
// or
function foo($first, string ...$other){}
PHP Arrays
Splat Operator
Into functions
$array = [1, 2];
function foo(int $a, int $b) {
echo $a; # => 1
echo $b; # => 2
}
foo(...$array);
Concatenate arrays
$a = [1, 2];
$b = [3, 4];
// PHP 7.4 later
# => [1, 2, 3, 4]
$result = [...$a, ...$b];
Key iteration
$arr = ["foo" => "bar", "bar" => "foo"];
foreach ( $arr as $key => $value )
{
echo "key: " . $key . "\n";
echo "val: {$arr[$key]}\n";
}
Value iteration
$colors = array('red', 'blue', 'green');
foreach ($colors as $color) {
echo "Do you like $color?\n";
}
Indexing iteration
$array = array('a', 'b', 'c');
$count = count($array);
for ($i = 0; $i < $count; $i++) {
echo "i:{$i}, v:{$array[$i]}\n";
}
Multi type
$array = array(
"foo" => "bar",
42 => 24,
"multi" => array(
"dim" => array(
"a" => "foo"
)
)
);
# => string(3) "bar"
var\_dump($array["foo"]);
# => int(24)
var\_dump($array[42]);
# => string(3) "foo"
var\_dump($array["multi"]["dim"]["a"]);
Multi array
$multiArray = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
print\_r($multiArray[0][0]) # => 1
print\_r($multiArray[0][1]) # => 2
print\_r($multiArray[0][2]) # => 3
Comments