0

I am a newbie in Php and this might be a quite basic question.

I would like to set string array and put values to array then get values which

I put to string array. so basically,

I want

ArrayList arr = new ArrayList<String>;
int limitSize = 20;
    for(i = 0; i < limitSize; i++){
          String data = i + "th";
          arr.add(data);
          System.out.println(arr.get(i));
    };

How can I do this in php?

0

3 Answers 3

4

It's far less verbose in PHP. Since it isn't strongly typed, you can just append any values onto the array. It can be done with an incremental for loop:

$array = array();
$size = 20;
for ($i = 0; $i < $size; $i++) {
  // Append onto array with []
  $array[] = "{$i}th"; 
}

...or with a foreach and range()

foreach (range(0,$size-1) as $i) {
  // Append onto array with []
  $array[] = "{$i}th";     
}

It is strongly recommended that you read the documentation on PHP arrays.

Sign up to request clarification or add additional context in comments.

2 Comments

range(0,$size - 1) to be equivalent to the for loop.
doesn't "$ith" look for the variable named $ith ?
2
$arr = array();
$limitSize = 20;
for($i = 0; $i < $limitSize; $i++){
      $data = $i . "th";
      $arr[] = $data;
      echo $arr[$i] . "\n";
}

Comments

0

In php arrays are always dynamic. so you can just use array_push($arrayName,$val) to add values and use regular for loop processing and do

for ($i=0; $i<count($arrName); $i++) {
    echo $arr[$i];
}

to print /get value at i.

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.