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?
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.
$arr = array();
$limitSize = 20;
for($i = 0; $i < $limitSize; $i++){
$data = $i . "th";
$arr[] = $data;
echo $arr[$i] . "\n";
}
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.
Related
I am in too much trouble. I need below type of array:-
$val = "abc";
$arr1["besk"] = $val
$arr2["besk"] = $val
.
.
$arr15["besk"] = $val
I tried below:-
for($i = 1; $i<16; $i++)
{
$arr.$i["besk"] = $val
}
here I've $val. so not to worry on that. But array is not properly creating. Any help would be appreciated.
first define the array as string
like
$arr = 'arr';
then use the foreach
like
for($i = 1; $i<16; $i++)
{
${$arr.$i}["besk"] = $val;
}
You need to use variable variables (not recommended)
for($i = 1; $i<16; $i++)
{
${"arr".$i}["besk"] = $val
}
EDIT : #CBroe is right about his comment, you should use an array instead. So the best solution would be to create a two dimensional array like so :
$arr = [];
for($i = 0; $i<15; $i++)
{
$arr[$i]["besk"] = $val
}
The only difference is your array indexes start from 0 now and if you want to have the third value of your array you need this command $arr[2]["besk"]
it is very simple use this:
for($i = 1; $i<16; $i++)
{
${$arr.$i}["besk"] = $val
}
Use this approach:
for($i = 1; $i<16; $i++)
{
${$arr.$i}["besk"] = $val;
}
add new variable
$val = "abc";
$arrName = "arr"; //this one
$arr1["besk"] = $val
$arr2["besk"] = $val
.
.
$arr15["besk"] = $val
and to call it
for($i = 1; $i<16; $i++)
{
${$arrName.$i}["besk"] = $val
}
ps. you did not create array, you just create 15 array variable with 1 index("besk" index)
My for loop should be adding 9 values to an array, but for some reason stops on 6. This only happens when I use the square bracket syntax to add the key and value to the array. Here's the code:
$sentences = $this->sentences($sentence);
$n = count($sentences);
echo $n;
$values = array();
for($i = 0; $i < $n; $i++){
$s1 = $sentences[$i];
for($j = 0; $j < $n; $j++){
$s2 = $sentences[$j];
$values[$i][$j] = $this->checkvalues($s1,$s2);
}
}
$sentences_dic = array();
$other = array();
$otherTwo = array();
for($i = 0; $i < $n; $i++){
$score = 0;
for($j = 0; $j < $n; $j++){
$score = $score+$values[$i][$j];
}
$other[$i] = $score;
$otherTwo[$i] = $sentences[$i];
$sentences_dic[($sentences[$i])]=$score;
var_dump($otherTwo);
}
//maybe need
return $sentences_dic;
I am not sure why this is happening. The array is only printing
Here is what it is printing. It should be printing the seventh, eigth and ninth terms but it isnt. All the terms it isn't adding were all able to print in the other and otherTwo arrays.
Array
(
[first] => banana
[second] => banana2
[third] => banana3
[fourth] => banana4
[fifth] => banana5
[sixth] => banana6
)
when it should be printing all 9 values and keys. I don't understand why I am able to add all sentences and scores to their full extent(9) to two seperate arrays, but when I try to use square bracket syntax it only goes to 6.
Given your output $sentences appears to be an array and has duplicates. Array keys must be unique and duplicate keys are overwritten.
You could do something like this for a multidimensional array:
if(isset($sentences_dic[$sentences[$i]])) {
$sentences_dic[$sentences[$i]][] = $score;
} else {
$sentences_dic[$sentences[$i]] = $score;
}
Or to sum the scores of duplicates:
if(isset($sentences_dic[$sentences[$i]])) {
$sentences_dic[$sentences[$i]] += $score;
} else {
$sentences_dic[$sentences[$i]] = $score;
}
I need to add * in an array. This is how i do it in javaScript.
function makeStarString(grade) {
var starArray = [];
var starString = "";
for (var i = 0; i < grade; i++){
starArray[i] = "*";
starString = starString.concat(starArray[i]);
}
return starString;
}
The javascript version works fine but I cant make it work with php.
This is as far as i got with php.
function makeStarString($varGrade) {
$starArray = array ();
$starString = "";
for ($i = 0; $i < strlen($varGrade); $i++){
$starArray($i) = $star;
$starString = $starString.(starArray(i));
}
return $starString;
}
I get this error "Fatal error: Can't use function return value in write context" because of line $starArray($i) = $star;
The argument I send to the function is an Integer.
So the purpose of the function is that if i send a 5 to the function it will return *****
How can i fix my php function?
Use $starArray[$i] instead of $starArray($i) and starArray(i).
If you really need stars in an array, you don't need to use a loop:
$starArray = array_fill(0, $varGrade, '*');
and if you need to turn the array into a string:
$starString = implode('', $starArray);
But if you don't really ever need to use the array of stars, it would be easier to just use str_repeat:
str_repeat('*', $varGrade);
It would generally be a great idea to use strlen($varGrade) in a variable, because the foreach loop will have to count the length every iteration. This might bring performance issues.
Your $star variable is not defined, so I have no idea what you're trying to put there. Revise your own code.
Finally, you may use the .= operator to add something to existing string.
function makeStarString($varGrade) {
$starArray = array ();
$starString = "";
$length = strlen($varGrade);
for ($i = 0; $i < $length; $i++){
$starArray[$i] = $star;
$starString .= $starArray[$i];
// equivalent to $starString = $starString . $starArray[$];
}
return $starString;
}
UPDATE
If you send an int to the function, you don't need strlen:
function makeStarString($varGrade) {
$starArray = array ();
$starString = "";
for ($i = 0; $i < $varGrade; $i++){
$starArray[$i] = $star;
$starString .= $starArray[$i];
// equivalent to $starString = $starString . $starArray[$];
}
return $starString;
}
This code should work
function makeStarString($varGrade) {
$star = "*"; // star variable wasn't defined to.
$starArray = array ();
$starString = "";
for ($i = 0; $i < $varGrade; $i++){
$starArray[$i] = $star; // [ ] instead of ( )
$starString .= ($starArray[$i]); // $a.=$b instead of $a=$a+$b, added the $ at the i and [ ] instead of ( )
}
return $starString;
}
Is this what you need?
function makeStarString($varGrade) {
$starString = '';
for ($i = 0; $i < $varGrade; $i++) {
$starString .= '*';
}
return $starString;
}
A few notes on my modifications.
I don't see why you need that $starArray array in the first place. So I skipped it.
I revised your indentation. Strange indentation can make very simple code seem much more complicated than it really is. :)
You should ask if $i < $varGrade, not if $i < strlen($varGrade). If you ask by strlen(), then you get the width of the number you enter. For example, strlen(55) is 2, strlen(555) is 3, strlen(5555) is 4 etc. - ignoring the fact that it's a number. You just want the for-loop to give you $varGrade many stars so there is no need for strlen().
As a detail, I've put used single-quotes instead of double-quotes for strings because they're lighter (PHP doesn't parse variables inside them).
I hope it helps.
I was wondering if it is possible to create unique variables in a for loop using PHP. I tried the following code but it didn't work:
$level_count = 6
for ($i=1; $i<=$level_count; $i++) {
$level_ + $i = array();
}
I would like to end up with the variables $level_1, $level_2, $level_3, $level_4, $level_5 and $level_6. How would I achieve this?
$level_count = 6
for ($i=1; $i<=$level_count; $i++) {
$l = "level" . $i;
$$l = array();
}
But Zerkms is right...
$arr = array(array(),array(),array(),array(),array(),array());
It's much easier if you use arrays for this. Try this one-liner:
$level_count = 6;
$array = array_fill_keys(array_map(function($index) {
return 'level_' . $index;
}, range(1, $level_count)), array());
var_dump($array);
Weird thing (I have no idea why you want to use it), but, just for educational purposes...
$level_count = 6;
for ($i = 1; $i <= $level_count; $i++) {
$name = 'level_' . $i;
$$name = array();
}
Hey is this the correct way to do concatenation? it does not seem to want to work for me!.
$driver1points = 0;
$driver2points = 0;
$driver3points = 0;
$driver4points = 0;
for($i = 1; $i <= 4; $++){
if(${"driver".$i} == $driverrace["fastestlap"]) {
${"driver". $i ."points"} += $driver_points_system["fastestlap"];
$racepoints += $team_points_system["fastestlap"];
break;
}
}
I agree with what is said in the comments. An array is a much better way to handle this.
<?php
$driver1points = 0;
$driver2points = 0;
$driver3points = 0;
$driver4points = 0;
for($i = 1; $i <= 4; $++) {
$driver = "driver$i";
if($$driver == $driverrace["fastestlap"]) {
${$driver."points"} += $driver_points_system["fastestlap"];
$racepoints += $team_points_system["fastestlap"];
break;
}
}
Can be translated into:
<?php
$drivers['bill'] = 0;
$drivers['ted'] = 0;
$drivers['cheech'] = 0;
$drivers['chong'] = 0;
foreach ( $drivers as $driver => &$points ) {
if ( $driver == $race['fastestlap'] ) {
echo "$driver had the fastest lap!";
$points += $driver_points_system['fastestlap'];
$racepoints += $team_points_system['fastestlap'];
break;
}
}
You can obviously do this as a numerative array and replace all of the $drivers[$driverName] assignments to just $drivers[]. I used an associative array to demonstrate that arrays are not only more efficient for this application, they can also be much easier to work with.
I passed the value argument of the foreach by reference, the "&" prefix (similar to a pointer, variable stores the memory address as opposed to the value); this allows you to directly manipulate the value in your logic as opposed to being given a copy of the value and needing to reassign with something similar to a $drivers[$driver] = $points;