PHP Array how to make it so that all arrays will have the same length
I have a multidimensional array. The arrays will have different lengths and seldom will they have the same length. My problem here is how can I make it so that the arrays will all share the length of the array with the biggest size?
My Array:
Array
(
[1] => Array
(
[Session 2] => Beer
[Food] => Chicken
[Drink] => Beer
)
[2] => Array
(
[Session 2] => Tea
[Food] => Aaaa
[Drink] => Ddd
[Cake] => Weee
[Brownies] => Rrrr
)
)
Expected output:
Array
(
[1] => Array
(
[Session 2] => Beer
[Food] => Chicken
[Drink] => Beer
[Cake] => ''
[Brownies] => ''
)
[2] => Array
(
[Session 2] => Tea
[Food] => Aaaa
[Drink] => Ddd
[Cake] => Weee
[Brownies] => Rrrr
)
)
The array size is not limited to only two arrays. Is this even possible and if so how?
I only want to copy the array keys and not the values its main purpose here is for presenting the content of the array in a table.
php arrays
add a comment |
I have a multidimensional array. The arrays will have different lengths and seldom will they have the same length. My problem here is how can I make it so that the arrays will all share the length of the array with the biggest size?
My Array:
Array
(
[1] => Array
(
[Session 2] => Beer
[Food] => Chicken
[Drink] => Beer
)
[2] => Array
(
[Session 2] => Tea
[Food] => Aaaa
[Drink] => Ddd
[Cake] => Weee
[Brownies] => Rrrr
)
)
Expected output:
Array
(
[1] => Array
(
[Session 2] => Beer
[Food] => Chicken
[Drink] => Beer
[Cake] => ''
[Brownies] => ''
)
[2] => Array
(
[Session 2] => Tea
[Food] => Aaaa
[Drink] => Ddd
[Cake] => Weee
[Brownies] => Rrrr
)
)
The array size is not limited to only two arrays. Is this even possible and if so how?
I only want to copy the array keys and not the values its main purpose here is for presenting the content of the array in a table.
php arrays
I suspect an object would be a better fit - you can define the properties then.
– CD001
Nov 13 '18 at 9:29
add a comment |
I have a multidimensional array. The arrays will have different lengths and seldom will they have the same length. My problem here is how can I make it so that the arrays will all share the length of the array with the biggest size?
My Array:
Array
(
[1] => Array
(
[Session 2] => Beer
[Food] => Chicken
[Drink] => Beer
)
[2] => Array
(
[Session 2] => Tea
[Food] => Aaaa
[Drink] => Ddd
[Cake] => Weee
[Brownies] => Rrrr
)
)
Expected output:
Array
(
[1] => Array
(
[Session 2] => Beer
[Food] => Chicken
[Drink] => Beer
[Cake] => ''
[Brownies] => ''
)
[2] => Array
(
[Session 2] => Tea
[Food] => Aaaa
[Drink] => Ddd
[Cake] => Weee
[Brownies] => Rrrr
)
)
The array size is not limited to only two arrays. Is this even possible and if so how?
I only want to copy the array keys and not the values its main purpose here is for presenting the content of the array in a table.
php arrays
I have a multidimensional array. The arrays will have different lengths and seldom will they have the same length. My problem here is how can I make it so that the arrays will all share the length of the array with the biggest size?
My Array:
Array
(
[1] => Array
(
[Session 2] => Beer
[Food] => Chicken
[Drink] => Beer
)
[2] => Array
(
[Session 2] => Tea
[Food] => Aaaa
[Drink] => Ddd
[Cake] => Weee
[Brownies] => Rrrr
)
)
Expected output:
Array
(
[1] => Array
(
[Session 2] => Beer
[Food] => Chicken
[Drink] => Beer
[Cake] => ''
[Brownies] => ''
)
[2] => Array
(
[Session 2] => Tea
[Food] => Aaaa
[Drink] => Ddd
[Cake] => Weee
[Brownies] => Rrrr
)
)
The array size is not limited to only two arrays. Is this even possible and if so how?
I only want to copy the array keys and not the values its main purpose here is for presenting the content of the array in a table.
php arrays
php arrays
asked Nov 13 '18 at 9:23
magicianiammagicianiam
52951851
52951851
I suspect an object would be a better fit - you can define the properties then.
– CD001
Nov 13 '18 at 9:29
add a comment |
I suspect an object would be a better fit - you can define the properties then.
– CD001
Nov 13 '18 at 9:29
I suspect an object would be a better fit - you can define the properties then.
– CD001
Nov 13 '18 at 9:29
I suspect an object would be a better fit - you can define the properties then.
– CD001
Nov 13 '18 at 9:29
add a comment |
3 Answers
3
active
oldest
votes
Here's one option, where you build an array of all possible array keys, then loop over your original array and set empty strings to the keys that don't exist yet:
// find all possible keys
$keys = ;
foreach ($array as $entry) {
$keys = array_merge($keys, array_keys($entry));
}
// pad missing keys with an empty string
foreach ($array as &$entry) {
foreach ($keys as $key) {
if (!isset($entry[$key])) {
$entry[$key] = '';
}
}
}
1
You don't need the inner loop + the if(). Use array_replace(keys, entry)
– Andreas
Nov 13 '18 at 9:33
@Andreas good point -$keys = ['Foo' => ''];then$entry = array_replace($entry, $keys)
– Robbie Averill
Nov 13 '18 at 9:35
thank you. will give this a try but what does this line mean?foreach ($array as &$entry) {the&$entry
– magicianiam
Nov 13 '18 at 9:37
1
I generally try to avoid modify by reference in loops because of the weird way PHP handles references. Even though it's a bit slower,array_walk()accomplishes the same thing without the possibility of weird side effects.
– Sam Leatherdale
Nov 13 '18 at 9:57
1
Is it not preferable to also usearray_fill_keysto just set all the values to the desired ones? So if he wishes to have all the keys and empty values to just do it as$emptyValuesArray = array_fill_keys(array_keys($targetArray), '');And avoid the for loops
– Diogo Santo
Nov 13 '18 at 11:12
|
show 1 more comment
If the main purpose is to show the data in a table, then you do not need to fill in the missing keys. You can use the isset() or empty() functions to determine whether an array has a given key. So, your table code could look like the following:
<?php
foreach ($rows as $row) {
echo "<tr>";
echo "<td>" . isset($row["Session 2"]) ? $row["Session 2"] : "" . "</td>"; //Old school
echo "<td>" . $row["Food"] ?? "" . "</td>"; //PHP 7+
//remaining rows
echo "</tr>";
}
1
The null coalescing operator could also be used here
– Karsten Koop
Nov 13 '18 at 9:46
@KarstenKoop Thanks, I've updated my answer with some better examples
– Sam Leatherdale
Nov 13 '18 at 9:52
add a comment |
Let's say the array you're talking about is inside a variable $array,
Do this to find the maximum length;
$max = 0;
foreach($array as $index => $value){
if($index == sizeof($array) - 1){
break;
}
if($index && $max > sizeof($array[$index+1])){
$max = $max;
}
if(!$index && sizeof($value) > sizeof($array[$index+1])){
$max = sizeof($value);
}else {
$max = sizeof($array[$index+1]);
}
}
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53277678%2fphp-array-how-to-make-it-so-that-all-arrays-will-have-the-same-length%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
Here's one option, where you build an array of all possible array keys, then loop over your original array and set empty strings to the keys that don't exist yet:
// find all possible keys
$keys = ;
foreach ($array as $entry) {
$keys = array_merge($keys, array_keys($entry));
}
// pad missing keys with an empty string
foreach ($array as &$entry) {
foreach ($keys as $key) {
if (!isset($entry[$key])) {
$entry[$key] = '';
}
}
}
1
You don't need the inner loop + the if(). Use array_replace(keys, entry)
– Andreas
Nov 13 '18 at 9:33
@Andreas good point -$keys = ['Foo' => ''];then$entry = array_replace($entry, $keys)
– Robbie Averill
Nov 13 '18 at 9:35
thank you. will give this a try but what does this line mean?foreach ($array as &$entry) {the&$entry
– magicianiam
Nov 13 '18 at 9:37
1
I generally try to avoid modify by reference in loops because of the weird way PHP handles references. Even though it's a bit slower,array_walk()accomplishes the same thing without the possibility of weird side effects.
– Sam Leatherdale
Nov 13 '18 at 9:57
1
Is it not preferable to also usearray_fill_keysto just set all the values to the desired ones? So if he wishes to have all the keys and empty values to just do it as$emptyValuesArray = array_fill_keys(array_keys($targetArray), '');And avoid the for loops
– Diogo Santo
Nov 13 '18 at 11:12
|
show 1 more comment
Here's one option, where you build an array of all possible array keys, then loop over your original array and set empty strings to the keys that don't exist yet:
// find all possible keys
$keys = ;
foreach ($array as $entry) {
$keys = array_merge($keys, array_keys($entry));
}
// pad missing keys with an empty string
foreach ($array as &$entry) {
foreach ($keys as $key) {
if (!isset($entry[$key])) {
$entry[$key] = '';
}
}
}
1
You don't need the inner loop + the if(). Use array_replace(keys, entry)
– Andreas
Nov 13 '18 at 9:33
@Andreas good point -$keys = ['Foo' => ''];then$entry = array_replace($entry, $keys)
– Robbie Averill
Nov 13 '18 at 9:35
thank you. will give this a try but what does this line mean?foreach ($array as &$entry) {the&$entry
– magicianiam
Nov 13 '18 at 9:37
1
I generally try to avoid modify by reference in loops because of the weird way PHP handles references. Even though it's a bit slower,array_walk()accomplishes the same thing without the possibility of weird side effects.
– Sam Leatherdale
Nov 13 '18 at 9:57
1
Is it not preferable to also usearray_fill_keysto just set all the values to the desired ones? So if he wishes to have all the keys and empty values to just do it as$emptyValuesArray = array_fill_keys(array_keys($targetArray), '');And avoid the for loops
– Diogo Santo
Nov 13 '18 at 11:12
|
show 1 more comment
Here's one option, where you build an array of all possible array keys, then loop over your original array and set empty strings to the keys that don't exist yet:
// find all possible keys
$keys = ;
foreach ($array as $entry) {
$keys = array_merge($keys, array_keys($entry));
}
// pad missing keys with an empty string
foreach ($array as &$entry) {
foreach ($keys as $key) {
if (!isset($entry[$key])) {
$entry[$key] = '';
}
}
}
Here's one option, where you build an array of all possible array keys, then loop over your original array and set empty strings to the keys that don't exist yet:
// find all possible keys
$keys = ;
foreach ($array as $entry) {
$keys = array_merge($keys, array_keys($entry));
}
// pad missing keys with an empty string
foreach ($array as &$entry) {
foreach ($keys as $key) {
if (!isset($entry[$key])) {
$entry[$key] = '';
}
}
}
answered Nov 13 '18 at 9:30
Robbie AverillRobbie Averill
20.8k74076
20.8k74076
1
You don't need the inner loop + the if(). Use array_replace(keys, entry)
– Andreas
Nov 13 '18 at 9:33
@Andreas good point -$keys = ['Foo' => ''];then$entry = array_replace($entry, $keys)
– Robbie Averill
Nov 13 '18 at 9:35
thank you. will give this a try but what does this line mean?foreach ($array as &$entry) {the&$entry
– magicianiam
Nov 13 '18 at 9:37
1
I generally try to avoid modify by reference in loops because of the weird way PHP handles references. Even though it's a bit slower,array_walk()accomplishes the same thing without the possibility of weird side effects.
– Sam Leatherdale
Nov 13 '18 at 9:57
1
Is it not preferable to also usearray_fill_keysto just set all the values to the desired ones? So if he wishes to have all the keys and empty values to just do it as$emptyValuesArray = array_fill_keys(array_keys($targetArray), '');And avoid the for loops
– Diogo Santo
Nov 13 '18 at 11:12
|
show 1 more comment
1
You don't need the inner loop + the if(). Use array_replace(keys, entry)
– Andreas
Nov 13 '18 at 9:33
@Andreas good point -$keys = ['Foo' => ''];then$entry = array_replace($entry, $keys)
– Robbie Averill
Nov 13 '18 at 9:35
thank you. will give this a try but what does this line mean?foreach ($array as &$entry) {the&$entry
– magicianiam
Nov 13 '18 at 9:37
1
I generally try to avoid modify by reference in loops because of the weird way PHP handles references. Even though it's a bit slower,array_walk()accomplishes the same thing without the possibility of weird side effects.
– Sam Leatherdale
Nov 13 '18 at 9:57
1
Is it not preferable to also usearray_fill_keysto just set all the values to the desired ones? So if he wishes to have all the keys and empty values to just do it as$emptyValuesArray = array_fill_keys(array_keys($targetArray), '');And avoid the for loops
– Diogo Santo
Nov 13 '18 at 11:12
1
1
You don't need the inner loop + the if(). Use array_replace(keys, entry)
– Andreas
Nov 13 '18 at 9:33
You don't need the inner loop + the if(). Use array_replace(keys, entry)
– Andreas
Nov 13 '18 at 9:33
@Andreas good point -
$keys = ['Foo' => '']; then $entry = array_replace($entry, $keys)– Robbie Averill
Nov 13 '18 at 9:35
@Andreas good point -
$keys = ['Foo' => '']; then $entry = array_replace($entry, $keys)– Robbie Averill
Nov 13 '18 at 9:35
thank you. will give this a try but what does this line mean?
foreach ($array as &$entry) { the &$entry– magicianiam
Nov 13 '18 at 9:37
thank you. will give this a try but what does this line mean?
foreach ($array as &$entry) { the &$entry– magicianiam
Nov 13 '18 at 9:37
1
1
I generally try to avoid modify by reference in loops because of the weird way PHP handles references. Even though it's a bit slower,
array_walk() accomplishes the same thing without the possibility of weird side effects.– Sam Leatherdale
Nov 13 '18 at 9:57
I generally try to avoid modify by reference in loops because of the weird way PHP handles references. Even though it's a bit slower,
array_walk() accomplishes the same thing without the possibility of weird side effects.– Sam Leatherdale
Nov 13 '18 at 9:57
1
1
Is it not preferable to also use
array_fill_keys to just set all the values to the desired ones? So if he wishes to have all the keys and empty values to just do it as $emptyValuesArray = array_fill_keys(array_keys($targetArray), ''); And avoid the for loops– Diogo Santo
Nov 13 '18 at 11:12
Is it not preferable to also use
array_fill_keys to just set all the values to the desired ones? So if he wishes to have all the keys and empty values to just do it as $emptyValuesArray = array_fill_keys(array_keys($targetArray), ''); And avoid the for loops– Diogo Santo
Nov 13 '18 at 11:12
|
show 1 more comment
If the main purpose is to show the data in a table, then you do not need to fill in the missing keys. You can use the isset() or empty() functions to determine whether an array has a given key. So, your table code could look like the following:
<?php
foreach ($rows as $row) {
echo "<tr>";
echo "<td>" . isset($row["Session 2"]) ? $row["Session 2"] : "" . "</td>"; //Old school
echo "<td>" . $row["Food"] ?? "" . "</td>"; //PHP 7+
//remaining rows
echo "</tr>";
}
1
The null coalescing operator could also be used here
– Karsten Koop
Nov 13 '18 at 9:46
@KarstenKoop Thanks, I've updated my answer with some better examples
– Sam Leatherdale
Nov 13 '18 at 9:52
add a comment |
If the main purpose is to show the data in a table, then you do not need to fill in the missing keys. You can use the isset() or empty() functions to determine whether an array has a given key. So, your table code could look like the following:
<?php
foreach ($rows as $row) {
echo "<tr>";
echo "<td>" . isset($row["Session 2"]) ? $row["Session 2"] : "" . "</td>"; //Old school
echo "<td>" . $row["Food"] ?? "" . "</td>"; //PHP 7+
//remaining rows
echo "</tr>";
}
1
The null coalescing operator could also be used here
– Karsten Koop
Nov 13 '18 at 9:46
@KarstenKoop Thanks, I've updated my answer with some better examples
– Sam Leatherdale
Nov 13 '18 at 9:52
add a comment |
If the main purpose is to show the data in a table, then you do not need to fill in the missing keys. You can use the isset() or empty() functions to determine whether an array has a given key. So, your table code could look like the following:
<?php
foreach ($rows as $row) {
echo "<tr>";
echo "<td>" . isset($row["Session 2"]) ? $row["Session 2"] : "" . "</td>"; //Old school
echo "<td>" . $row["Food"] ?? "" . "</td>"; //PHP 7+
//remaining rows
echo "</tr>";
}
If the main purpose is to show the data in a table, then you do not need to fill in the missing keys. You can use the isset() or empty() functions to determine whether an array has a given key. So, your table code could look like the following:
<?php
foreach ($rows as $row) {
echo "<tr>";
echo "<td>" . isset($row["Session 2"]) ? $row["Session 2"] : "" . "</td>"; //Old school
echo "<td>" . $row["Food"] ?? "" . "</td>"; //PHP 7+
//remaining rows
echo "</tr>";
}
edited Nov 13 '18 at 9:52
answered Nov 13 '18 at 9:31
Sam LeatherdaleSam Leatherdale
11517
11517
1
The null coalescing operator could also be used here
– Karsten Koop
Nov 13 '18 at 9:46
@KarstenKoop Thanks, I've updated my answer with some better examples
– Sam Leatherdale
Nov 13 '18 at 9:52
add a comment |
1
The null coalescing operator could also be used here
– Karsten Koop
Nov 13 '18 at 9:46
@KarstenKoop Thanks, I've updated my answer with some better examples
– Sam Leatherdale
Nov 13 '18 at 9:52
1
1
The null coalescing operator could also be used here
– Karsten Koop
Nov 13 '18 at 9:46
The null coalescing operator could also be used here
– Karsten Koop
Nov 13 '18 at 9:46
@KarstenKoop Thanks, I've updated my answer with some better examples
– Sam Leatherdale
Nov 13 '18 at 9:52
@KarstenKoop Thanks, I've updated my answer with some better examples
– Sam Leatherdale
Nov 13 '18 at 9:52
add a comment |
Let's say the array you're talking about is inside a variable $array,
Do this to find the maximum length;
$max = 0;
foreach($array as $index => $value){
if($index == sizeof($array) - 1){
break;
}
if($index && $max > sizeof($array[$index+1])){
$max = $max;
}
if(!$index && sizeof($value) > sizeof($array[$index+1])){
$max = sizeof($value);
}else {
$max = sizeof($array[$index+1]);
}
}
add a comment |
Let's say the array you're talking about is inside a variable $array,
Do this to find the maximum length;
$max = 0;
foreach($array as $index => $value){
if($index == sizeof($array) - 1){
break;
}
if($index && $max > sizeof($array[$index+1])){
$max = $max;
}
if(!$index && sizeof($value) > sizeof($array[$index+1])){
$max = sizeof($value);
}else {
$max = sizeof($array[$index+1]);
}
}
add a comment |
Let's say the array you're talking about is inside a variable $array,
Do this to find the maximum length;
$max = 0;
foreach($array as $index => $value){
if($index == sizeof($array) - 1){
break;
}
if($index && $max > sizeof($array[$index+1])){
$max = $max;
}
if(!$index && sizeof($value) > sizeof($array[$index+1])){
$max = sizeof($value);
}else {
$max = sizeof($array[$index+1]);
}
}
Let's say the array you're talking about is inside a variable $array,
Do this to find the maximum length;
$max = 0;
foreach($array as $index => $value){
if($index == sizeof($array) - 1){
break;
}
if($index && $max > sizeof($array[$index+1])){
$max = $max;
}
if(!$index && sizeof($value) > sizeof($array[$index+1])){
$max = sizeof($value);
}else {
$max = sizeof($array[$index+1]);
}
}
edited Nov 13 '18 at 9:44
Robbie Averill
20.8k74076
20.8k74076
answered Nov 13 '18 at 9:41
Jolaosho batmatJolaosho batmat
195
195
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53277678%2fphp-array-how-to-make-it-so-that-all-arrays-will-have-the-same-length%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
I suspect an object would be a better fit - you can define the properties then.
– CD001
Nov 13 '18 at 9:29