My aim is to create an array having N length with pre filled column names with PHP
. Here is an example,
if N = 5; then
$test_array = array('column1', 'column2', 'column3', 'column4', 'column5');
I tried array_fill
function, but the array values are same. Can someone suggest me a better method ?
Update
This is how it looks while using array_fill
. I know, i can use foreach
and solve this within a fraction of seconds, what i'm searching for a one line method; if exists.
<?php
$n = 5;
$test_array = array_fill(0, $n, 'column');
echo print_r($test_array, true);
?>
Result : Array ( [0] => column [1] => column [2] => column [3] => column [4] => column )
I guess this is what you are looking for, considering you wrote of "column names" to be prefilled:
<?php
$test_array = [];
for ($i=0; $i<5; $i++) {
$test_array['column'.$i] = null;
}
var_dump($test_array);
This will create this output:
array(5) {
'column0' => NULL
'column1' => NULL
'column2' => NULL
'column3' => NULL
'column4' => NULL
}
If instead you are looking for "column values", so array elements being prefilled, then try that:
<?php
$test_array = [];
for ($i=0; $i<5; $i++) {
$test_array[] = 'column'.$i;
}
var_dump($test_array);
That will create this output:
array(5) {
0 => 'column0'
1 => 'column1'
2 => 'column2'
3 => 'column3'
4 => 'column4'
}
In Php an array is dynamic at all . You don't need to set its length.. As per your need you may create an array to serve as key(column names) and then combine it to values containing array . Try follwing -
$column_array=array('column1', 'column2', 'column3', 'column4', 'column5');
$value_array=array('a','b','c','d','e');
$reslut=array_combine($column_array,$value_array);
print_r($result);
Output
Array ( [column1] => a [column2] => b [column3] => c [column4] => d [column5] => e )
array_combine needs both array have same length . As your condition stays ,it may be some columns might ave null values .To work in that condition do as follow-
$column_array=array('column1', 'column2', 'column3', 'column4', 'column5');
$value_array=array('a','b','c','d');
$value_array +=array_fill(
count($value_array),
count($column_array)-
count($value_array),null);
//filling array upto column array length
$result=array_combine($column_array,$value_array);
print_r($result);
Output
Array ( [column1] => a [column2] => b [column3] => c [column4] => d [column5] => )
<?php
$array = [];
for ($i=0; $i<5; $i++) {
$array['column'.$i] = null;
}
die($array);
?>