3

My code:

$a = array_fill(5, 6, 'banana');

prints

Array
(
    [5]  => banana
    [6]  => banana
    [7]  => banana
    [8]  => banana
    [9]  => banana
    [10] => banana
)

But I wanted it something like below

Array
(
    [5]  => banana 1
    [6]  => banana 2
    [7]  => banana 3
    [8]  => banana 4
    [9]  => banana 5
    [10] => banana 6
)

Is there any other php function there to achieve above? If yes, could you please let me know.

5
  • 3
    Why don't you do your own ?, it's quite easy actually Commented Aug 14, 2012 at 15:55
  • 1
    use foreach loop and its rly easy :D Commented Aug 14, 2012 at 15:56
  • I know how to produce above using for/foreach/while loops but I thought there might be something there to increment the number alongwith the string value, so the question. Commented Aug 14, 2012 at 15:58
  • 1
    @user1421214 no there is not. Commented Aug 14, 2012 at 15:59
  • KalpeshMehta's comment should be the correct answer. btw couldn't you search php manual? i think it takes less time to write the code than asking this question Commented Aug 14, 2012 at 16:00

4 Answers 4

2
function test_print_value($item2, $key, $some_value)
{
    echo $some_value." $item2<br />\n";
}

array_walk(range(0,10), 'test_print_value', 'Banana Apple ');

Output:

Banana Apple 0
Banana Apple 1
Banana Apple 2
Banana Apple 3
Banana Apple 4
Banana Apple 5
Banana Apple 6
Banana Apple 7
Banana Apple 8
Banana Apple 9
Banana Apple 10
Sign up to request clarification or add additional context in comments.

Comments

2

Not out of the box, but you can write it yourself easily:

<?php
function custom_array_fill($start_index, $num, $value) {
    $result = array();
    for($i = 1; $i < $num + 1; $i++) {
        $result[$start_index + $i - 1] = $value . " " . $i;
    }
    return $result;
}

2 Comments

@shiplu.mokadd.im That comment was added after I posted my answer. I am not psychic.
oops. apology. but i think you can edit your answer to reflect the information
1

Perhaps you can use array_walk function?

$a = array_fill(5, 6, 'banana');
array_walk($a, function(&$item, $key) {
    $item = sprintf('%s %d', $item, ($key-4));//subtract 4 from key to get 'banana 1'
});

Just do not forget to pass $item as a reference (with the & character). Otherwise, you will not modify your array.

Comments

0
function myFillArray($index,$size,$value){
    $array = array();
    for($i = 0; $i < $size; $i++){
        $array[$index + $i] = $value." ".$i;        
    }
    return $array;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.