2

I am trying to create an array based on the value of a string (integer), for example:

// my string
$dogs = '2';

// my array
$dogs_array = array(
                [0] => 'Dog 1',
                [1] => 'Dog 2'
              );

So if the string was 4 there would be 4 items in the array. Is this possible? If so how can this be done?

Thanks in advance.

1
  • With for or foreach Commented Oct 13, 2016 at 14:47

3 Answers 3

5
$i = 1;
$dogs_count = (int)$dogs;
while ($i <= $dogs_count) {
    $dogs_array[] = 'Dog ' . $i++;
}
print_r($dogs_array);
Sign up to request clarification or add additional context in comments.

2 Comments

I think you should use loop index in $dogs_array[].
@Mohammad Why should an index be used? PHP automatically increments a numeric index for you, so no need to do it in your code
1
<?php
// my string
$dogs = '5'; //initialize your variable

$dogsArray = array(); // initialize an empty array

for($i =1; $i <= $dogs; $i++)
{
    array_push($dogsArray, 'Dog '.$i);
}

var_dump($dogsArray);

?>

Comments

0
$count = (int) $dogs;
$dogs_array = [];
for($i = 0;$count>$i; $i++){
    $dogs_array[$i] = "Dogs ".$i;
}
print_r($dogs_array);

1 Comment

While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.

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.