2

I have a PHP array which looks like this...

array
(
[0] => apple,
[1] => orange,
)

I need to ensure the array contains 4 items, so in the instance above I want to end up with this...

array
(
[0] => apple,
[1] => orange,
[2} => ,
[3] => ,
)

Am I best looping through this with a counter and creating a new array, or is there a better method?

1

3 Answers 3

6

Pad your array with elements to a size that you need:

$my_arr = [1,2];
$my_arr = array_pad($my_arr, 4, '');
Sign up to request clarification or add additional context in comments.

3 Comments

Would this work if I don't know the number of elements in the array?
Why not? You pad array to required size. Number of required elements will be counted as required size minus current size.
@fightstarr20 Yes. According to the docs - "...if the absolute value of size is less than or equal to the array length, no padding takes place." so it won't affect your array if the array already exceeds 4 elements. It will only pad arrays with length 4 - count($my_arr) >= 1...
1

This should do what you're after

$iNumberOfElements = 5;

$a = array('apple', 'orange');

if(count($a) < $iNumberOfElements){
    while (count($a) < $iNumberOfElements) {
        $a[] = "";
    }
}

var_dump($a);
exit;

Comments

1

as @iainn said: php.net/manual/en/function.array-pad.php

there is this function:

$input = array(12, 10, 9);

$result = array_pad($input, 5, 0);
// result is array(12, 10, 9, 0, 0)

5 is the size of your array, 0 is the default value to empty cells

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.