populating an array with a for loop in php - php

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.

Related

PHP Loop Stuck on one character

i have some problem.
i just want my loop to run, but when i try to do it, it fails, it has to increment each letter by a few, but it doesn't take any new letters at all, why is this happening and what is the reason? in c ++ such code would work.
function accum('ZpglnRxqenU') {
// your code
$result = '';
$letters_result = '';
$letter_original = '';
$num_if_str = strlen($s);
$j = 0;
for ( $i=0; $i <= $num_if_str; $i++ )
{
$letter_original = substr($s, $i, $i+1);
$j = 0;
while($j == $i)
{
$letters_result = $letters_result . $letter_original;
$j++;
}
if($i != strlen($s))
{
$letters_result = $letters_result . '-';
}
}
return $letters_result;
}
It returns
- Expected: 'Z-Pp-Ggg-Llll-Nnnnn-Rrrrrr-Xxxxxxx-Qqqqqqqq-Eeeeeeeee-Nnnnnnnnnn-Uuuuuuuuuuu'
Actual : 'Z-----------'
what problem with what PHP code?
There are a number of problems here:
you're using $s but never initialise it
Your call to substr() uses an incorrect value for the length of substring to return
you're inner loop only runs while $i = $j, but you initialise $j to 0 so it will only run when $i is zero, i.e. for the first letter of the string.
There is a simpler way to do this. In PHP you can address individual characters in a string as if they were array elements, so no need for substr()
Further, you can use str_repeat() to generate the repeating strings, and if you store the expanded strings in an array you can join them all with implode().
Lastly, combining ucwords() and strtolower() returns the required case.
Putting it all together we get
<?php
$str = "ZpglnRxqenU";
$output = [];
for ($i = 0;$i<strlen($str);$i++) {
$output[] = str_repeat($str[$i], $i+1);
}
$output = ucwords(strtolower(implode('-',$output)),"-");
echo $output; // Z-Pp-Ggg-Llll-Nnnnn-Rrrrrr-Xxxxxxx-Qqqqqqqq-Eeeeeeeee-Nnnnnnnnnn-Uuuuuuuuuuu
Demo:https://3v4l.org/OoukZ
I don't have much more to add to #TangentiallyPerpendicular's answer as far as critique, other than you've made the classic while($i<=strlen($s)) off-by-one blunder. String bar will have a length of 3, but arrays are zero-indexed [eg: [ 0 => 'b', 1 => 'a', '2' => 'r' ]] so when you hit $i == strlen() at 3, that's an error.
Aside from that your approach, when corrected and made concise, would look like:
function accum($input) {
$result = '';
for ( $i=0, $len=strlen($input); $i < $len; $i++ ) {
$letter = substr($input, $i, 1);
for( $j=0; $j<=$i; $j++ ) {
$result .= $letter;
}
if($i != $len-1) {
$result .= '-';
}
}
return $result;
}
var_dump(accum('ZpglnRxqenU'));
Output:
string(76) "Z-pp-ggg-llll-nnnnn-RRRRRR-xxxxxxx-qqqqqqqq-eeeeeeeee-nnnnnnnnnn-UUUUUUUUUUU"
Also keep in mind that functions have their own isolated variable scope, so you don't need to namespace variables like $letters_foo which can make your code a bit confusing to the eye.

How do i rand string according to index size

I don't really know how to go about but it really pretty for me in achievement like each rand_string to each index.
My code:
function rand_string($length) {
$str="";
$chars = "abcdefghijklmanopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$size = strlen($chars);
for($i = 0; $i < $length; $i++) {
$str .= $chars[rand(0, $size-1)];
}
return $str;
}
$pcode = rand_string(4);
for ($b = 0; $b < 3; $b++) {
echo $pcode[$b];
}
I am expecting something like: 9cwm cZnu c9e4 in the output. Can I achieve this in PHP?
Currently, with my code, I get a string from rand_string in each index like 9cw.
Your code works, you only need to call rand_string inside your second loop in order to get something like 9cwm cZnu c9e4 (what you have described in your question).
Here is a working example:
function rand_string($length) {
$str="";
$chars = "abcdefghijklmanopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$size = strlen($chars);
for($i = 0;$i < $length;$i++) {
$str .= $chars[rand(0,$size-1)];
}
return $str;
}
// call rand_string inside for loop
for ($b = 0; $b<3; $b++) {
echo rand_string(4).' ';
}
Try it online
The generation of the string actually works in your code. You aren't calling/printing the function correctly. Just call the function three times and print all the results (with spaces in between). Instead of printing you could join it together in a string and remove the last space.
<?php
function rand_string($length) {
$str="";
$chars = "abcdefghijklmanopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$size = strlen($chars);
for($i = 0;$i < $length;$i++) {
$str .= $chars[rand(0,$size-1)];
}
return $str;
}
for ($b = 0; $b<3; $b++)
{
echo rand_string(4)." ";
}
If you don't mind using a completely different approach, limited to 32 chars :
return substr(md5(mt_rand().time()), 0, $length);
It's not super random but you get the picture...
Thanks to CM and user2693053 for bringing stuff to my attention (updated answer)
using mt_rand() instead of rand()
md5() length of 32...

How do I generate more than one random code

I have typed this up to generate a random code. I am trying to add them into a database as they are generated. How do i modify this code to generate x amount instead of one?
<?php
$tokens = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$serial = '';
for ($i = 0; $i < 4; $i++) {
for ($j = 0; $j < 5; $j++) {
$serial .= $tokens[rand(0, 35)];
}
if ($i < 3) {
$serial .= '-';
}
}
echo '<p>' . $serial;
?>
for more precise random token. Try adding current timestamp with a text. current Timestamp itself changes every second. therefore it will mostly be unique. A random text adding at front or last can make it even more unique for users working at a same time.
UPDATE: also add a function whether that unique string exists or not.
A pretty cool, easy method, can be something like this too.
<?php
echo md5(microtime());
Ofcourse it is not 100% safe etc but if you need a quick and easy "RANDOM" string it could be usefull.
Concerning your question:
<?php
function genereteRandomKey($count=10)
{
$data = [];
for($i=0;$i<$count;$i++)
{
$data[] = md5(microtime());
}
return $data;
}
var_dump(generateRandomKey());
To do this, we edit your code slightly and wrap it within a function, like this;
function createHash($length = 4)
{
$tokens = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$serial = '';
for ($it = 0; $it < $length; $it++) {
$serial .= $tokens[ mt_rand( 0, (strlen($tokens) - 1) )];
}
return $serial;
}
The length within the parameter can be left null and will default to 4, just in case you wanted to create longer codes.
To then create more codes, you simply loop via a for loop (Or any loop that you are using!) like so;
for ($i = 0; $i < 5; $i++) {
echo createHash() . '<br />';
}
Obviously, you won't be wishing to echo them out, but instead adding them to a database.
With that in mind, may I also suggest that instead of multiple INSERT queries, to catch them all inside of an array and just do one run on the query, which can be achieved like so;
$inserts = array ();
for ($i = 0; $i < 5; $i++) {
$inserts[] = createHash();
}
$sql = "INSERT INTO `table` (`row`) VALUES ('" . implode('\'), (\'', $inserts) . ");";
Which, in that test run, would output the following as your $sql;
INSERT INTO `table` (`row`) VALUES ('ISS7'), ('SB72'), ('N97I'), ('1WLQ'), ('TF6I);

set string array from php?

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.

How to iterate over an array of objects without foreach and ArrayAccess

I'm having to develop a site on PHP 5.1.6 and I've just come across a bug in my site which isn't happening on 5.2+. When using foreach() to iterate over an object, I get the following error: "Fatal error: Objects used as arrays in post/pre increment/decrement must return values by reference..."
Does anyone know how to convert the following foreach loop to a construct which will work with 5.1.6? Thanks in advance!
foreach ($post['commercial_brands'] as $brand)
{
$comm_food = new Commercial_food_Model;
$comm_food->brand = $brand;
$comm_food->feeding_type_id = $f_type->id;
$comm_food->save();
}
Improving upon Coronatus's answer:
$max = count($post['commercial_brands']);
for ($i = 0; $i < $max; $i++)
{
$comm_food = new Commercial_food_Model;
$comm_food->brand = $post['commercial_brands'][$i];
$comm_food->feeding_type_id = $f_type->id;
$comm_food->save();
}
You should never have a function in the condition of a loop, because each time the loop goes around it will run the function.
$x = 0;
$length = count($post['commercial_brands']);
while($x < $length){
$comm_food = new Commercial_food_Model;
$comm_food->brand = $post['commercial_brands'][$x];
$comm_food->feeding_type_id = $f_type->id;
$comm_food->save();
$x++;
}
//while 4 eva
for ($i = 0; $i < count($post['commercial_brands']); $i++)
{
$comm_food = new Commercial_food_Model;
$comm_food->brand = $post['commercial_brands'][$i];
$comm_food->feeding_type_id = $f_type->id;
$comm_food->save();
}

Categories