php- code make it small - php

I am trying to make this code small using for or while loop . It is working with the following code,I just want this to be small. 'ufile' is the input name.
if (!$_FILES['ufile']['name'][0])
{
echo "Upload 1st file";
}
else
{
// can this be in a for loop???
$path1= "../uploads/".$_FILES['ufile']['name'][0];
$path2= "../uploads/".$_FILES['ufile']['name'][1];
$path3= "../uploads/".$_FILES['ufile']['name'][2];
$path4= "../uploads/".$_FILES['ufile']['name'][3];
$path5= "../uploads/".$_FILES['ufile']['name'][4];
$path6= "../uploads/".$_FILES['ufile']['name'][5];
$path7= "../uploads/".$_FILES['ufile']['name'][6];
$path8= "../uploads/".$_FILES['ufile']['name'][7];
}

$path = array();
for($i=0;$i<=7;++$i)
$path[$i]="../uploads/".$_FILES['ufile']['name'][$i];

I would advise against your current coding style. Life would be simpler if you just stored the paths in an array, e.g.
$paths[1] = "../uploads/" . $_FILES['ufile']['name'][0];
$paths[2] = "../uploads/" . $_FILES['ufile']['name'][1];
Then you could do something like this:
$paths = array();
for ($i = 0; $i <= 7; $i++) {
$paths[$i + 1] = $_FILES['ufile']['name'][$i];
}
But to answer your question, you can do something like this instead, which is very similar:
$paths = array();
for ($i = 0; $i <= 7; $i++) {
$paths['path' . ($i + 1)] = $_FILES['ufile']['name'][$i];
}
extract($paths);
See the extract doc page for more info about what's going on here

You can use variable variables as well :
foreach(range(0,7) as $index){
$varname = "path".$index;
$$varname = "../uploads/".$_FILES['ufile']['name'][$index];
}

Not sure what you want to do with those paths afterwards but here is my go at it. I would use the length of the array, assuming it doesn't always contain the same amount of file names.
$paths = array();
for($i = 0; $i < count($_FILES['ufile']['name']); $i++)
{
$paths[] = "../uploads/".$_FILES['ufile']['name'][$i];
}

Related

dynamic array variable with dynamic values

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)

How to change the value with a variable within a for loop?

I have the following code:
$extraPhoto_1 = get_field('extra_photo_1');
$extraPhoto_2 = get_field('extra_photo_2');
$extraPhoto_3 = get_field('extra_photo_3');
$extraPhoto_4 = get_field('extra_photo_4');
But I would like to rewrite it with a for loop, but I can't figure out how to put a variable within the value field. What I have so far is:
for($i = 1; $i < 5; $i++) {
${'extraPhoto_' . $i} = get_field('extra_photo_ . $i');
}
I've tried with an array like this:
$myfiles = array();
for ($i = 1; $i < 5; $i++) {
$myfiles["$extraPhoto_$i"] = get_field('extra_photo_ . $i');
}
Nothing seems to fix my problem. I'v searched on the PHP website (variable variable).
There is some bug in your code which not allowing. Use 'extra_photo_'. $i instead of 'extra_photo_. $i'
for($i = 1; $i < 5; $i++) {
$extraPhoto_.$i = get_field('extra_photo_'. $i);
}
You can build an array as defined below and than just call extract($myfiles) to access them as variables.
Again your syntax for the get field is incorrect you should append $i after the quotes.
$myfiles = array();
for ($i = 1; $i < 5; $i++) {
$myfiles["extraPhoto_".$i] = get_field('extra_photo_'.$i);
}
extract($myfiles);
If you want to create dynamic variable, use below code
for ($i = 1; $i < 5; $i++) {
${'extraPhoto_'.$i} = $_POST['extra_photo_'.$i];
}
if you want to assign variables to array use below code.
for ($i = 1; $i < 5; $i++) {
$myfiles["extraPhoto_$i"] = $_POST['extra_photo_'.$i];
/// $myfiles["extraPhoto_$i"] = get_field('extra_photo_'.$i);
}
and than to see if values are assign to new array or not, you can use below code.
echo "<pre>";print_r($myfiles);echo "</pre>";

PHP: Create Unique Variables In A For Loop

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();
}

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);

Create 100 variables in php with autoincrement

I need to create a php file with a hundred variables, which are all identical except for their id.
PHP Code
$myvar1 = get_input('myvar1');
$myvar2 = get_input('myvar2');
$myvar3 = get_input('myvar3');
$myvar4 = get_input('myvar4');
...
$myvar100 = get_input('myvar100');
I wonder if it is possible to create only one line as a model, and is replicated 100 times?
Thanks.
Just store it in an array instead of 100 variables:
$myvar = Array();
for ($i = 1; $i <= 100; ++$i) {
$myvar[$i] = get_input('myvar' . $i);
}
Or if you want the indexes to start at zero:
$myvar = Array();
for ($i = 1; $i <= 100; ++$i) {
$myvar[$i - 1] = get_input('myvar' . $i);
}
You really must use Arrays for this, its far more appropriate:
$myvar = Array();
for($i=1;$i<101;$i++) $myvar[$i]=get_input("myvar{$i}"); // $myvar[1]=... etc...
Anyway, its possible to create variable names dynamically (notice the '$$'):
for($i=1;$i<101;$i++){
$varName="myvar{$i}";
$$varName=get_input($varName);
}
you could store your variables in an array
$myvarArr = array();
for($i=0;i<100;i++) {
$myvarArr[$i] = get_input('myvar' . ($i+1));
}
Looks like you just need an array, an array right from the outside variable.
if you make your form field name like this
<input type="text" name="myvar[]">
<input type="text" name="myvar[]">
<input type="text" name="myvar[]">
<input type="text" name="myvar[]">
you can easily get all the values by as simple code as
$myvar = $_POST['myvar'];
Just to show, that it's possible, use variable variables (i just love this php feature):
for ($i = 1; $i <= 100; $i++) {
$varName = "myvar{$i}"; // create variable name
$$varName = get_input("myvar{$i}"); // $$varName => $myvar5, when $i == 5 and so on
}

Categories