I'm having some doubt doing some for each loop, so i have an immense variable names ranging from $a1 - $a120
What I'm trying to do is doing a for each loop from where I can get each of thoose by using an indexing system.
$a116= "N69";
$a117= "V52";
$a118= "V53";
$a119= "V54";
$a120= "V55";
# FIM
for ($i = 0; $i <= 119; ++$i) {
$var = ${"a".$i}; // This is what i need to learn to do
$sheet->setCellValue($var, $array[$i]); // the array is other information im inserting to the file
}
It is not good for the loops. But you can use it, if you can not change your codes.
I just added
$var_name="a".$i;
$var = $$var_name;
And the full code is below.
$a116= "N69";
$a117= "V52";
$a118= "V53";
$a119= "V54";
$a120= "V55";
# FIM
for ($i = 0; $i <= 119; ++$i) {
$var_name="a".$i;
$var = $$var_name; // This is what i need to learn to do
$sheet->setCellValue($var, $array[$i]); // the array is other information im inserting to the file
}
You should update the code to use an array.
$data = [];
$data["a116"] = "N69";
$data["a117"] = "V52";
$data["a118"] = "V53";
$data["a119"] = "V54";
$data["a120"] = "V55";
Now you can use a foreach loop getting the key/value pairs
foreach($data as $key => $value){
$sheet->setCellValue($key, $value);
}
Related
How can I have same data stored as much as provided number?
Example
Store abc, 10 times
both abc and 10 are coming from form request
Code
nonuiqueAmount: 10
nonuiqueSerial: "abc"
if(!empty($request->input('nonuiqueSerial'))) {
foreach($request->input('nonuiqueAmount') as $item) { // this returns error
$barcode = new Barcode;
$barcode->serial_number = $request->input('nonuiqueSerial');
$barcode->save();
}
}
Error:
Invalid argument supplied for foreach()
You should use a for loop:
// nonuiqueAmount: 10
// nonuiqueSerial: "abc"
if (!empty($request->input('nonuiqueSerial'))) {
for ($i = 0; $i < $request->input('nonuiqueAmount', 0); ++$i) { // I've added the zero as a default value to prevent unnecessary loops
$barcode = new Barcode;
$barcode->serial_number = $request->input('nonuiqueSerial');
$barcode->save();
}
}
The foreach loop works only on arrays, and is used to loop through each key/value pair in an array. w3schools docs
Your nonuiqueAmount is an int. I would suggest simply stick with basic for loop
for ($x = 0; $x < $request->input('nonuiqueAmount'); $x++) {
$barcode = new Barcode;
$barcode->serial_number = $request->input('nonuiqueSerial');
$barcode->save();
}
I am looking for a PHP solution to use a loop to go through to capture all the data
Here is an example of a lookup without using a loop
if (array_key_exists('utf8String', $cert['tbsCertificate']['subject']['rdnSequence'][0][0]['value'])) {
// do somthing
} else if (array_key_exists('printableString', $cert['tbsCertificate']['subject']['rdnSequence'][0][0]['value'])) {
// do somthing
} else if (array_key_exists('bmpString', $cert['tbsCertificate']['subject']['rdnSequence'][0][0]['value'])) {
// do somthing
} else if (array_key_exists('telextexString', $cert['tbsCertificate']['subject']['rdnSequence'][0][0]['value'])) {
// do somthing
}
I need the loop to go through the entire array. For ONLY the first [ ] the loop should increase the integer [0] to 1, [2] and so forth until its gone through the whole lot. In case you are wondering, the second [ ] is always [0] so that needs to remain as is.
Right now I am copying/pasting the above about 20 times and manually updating the number in the first box but I am hoping there is a more elegant way to achieve that.
-- MORE CONTEXT --
-- WORKING CODE -- offered by #Ghost
$count = count($cert['tbsCertificate']['subject']['rdnSequence']);
$exists = array('utf8String', 'printableString', 'teletexString');
$oid = array('id-at-stateOrProvinceName', 'id-at-countryName', 'id-at-localityName', 'id-at-commonName', 'id-at-organizationalUnitName');
for($i = 0; $i < $count; $i++) {
foreach($exists as $field) {
if(array_key_exists($field, $cert['tbsCertificate']['subject']['rdnSequence'][$i][0]['value'])) {
$value = $cert['tbsCertificate']['subject']['rdnSequence'][$i][0]['value'][$field];
echo $value, ' [',$field, ']',"\n";
}
}
}
You can just add another loop inside applying each field into array_key_exists, this applies to #Markus' idea anyway:
$count = count($cert['tbsCertificate']['subject']['rdnSequence']);
$exists = array('utf8String', 'printableString', 'teletexString');
$oid = array('id-at-stateOrProvinceName', 'id-at-countryName', 'id-at-localityName', 'id-at-commonName', 'id-at-organizationalUnitName');
for($i = 0; $i < $count; $i++) {
foreach($exists as $field) {
if(array_key_exists($field, $cert['tbsCertificate']['subject']['rdnSequence'][$i][0]['value'])) {
$value = $cert['tbsCertificate']['subject']['rdnSequence'][$i][0]['value'][$field];
$k = array_keys($cert['tbsCertificate']['subject']['rdnSequence'][$i][0]['type']);
$oid = reset($k);
break;
}
}
}
[ EDIT: Please see the comments below. ] How about for simples...
$strings = ['utf8String', 'printableString' ... ];
foreach ($strings as $string) { // do your checks etc. }
I suppose you know how to increment a counter in a loop. $i++ and stuff, use [$i] wherever you need to increment the reference value in your $cert array. On match, break or continue in place of else if, depending on what exactly you need to accomplish here. Your objectives aren't too clear in the question, could share a bit more insight...
define('HOUSEHOLD_CHILD1','custom_16');
define('HOUSEHOLD_CHILD2','custom_14');
define('HOUSEHOLD_CHILD3','custom_13');
define('HOUSEHOLD_CHILD4','custom_12');
function household_function() {
$vari = array();
$var['household'][HOUSEHOLD_CHILD1] = $_SESSION['household_membership'][1];
$var['household'][HOUSEHOLD_CHILD2] = $_SESSION['household_membership'][2];
$var['household'][HOUSEHOLD_CHILD3] = $_SESSION['household_membership'][3];
}
I want to implement the above code in foreach loop
like something similar to concatenate.
it should be something similar to this
foreach($_SESSION['household'] as $key => $value) {
$var['household'][HOUSEHOLD_CHILDi] = [i];//i need to concatenate the constant
//to something similar we do for string
}
The constant function will serve your purpose:
define('HOUSEHOLD_CHILD1','custom_16');
define('HOUSEHOLD_CHILD2','custom_14');
define('HOUSEHOLD_CHILD3','custom_13');
define('HOUSEHOLD_CHILD4','custom_12');
for($i = 1; $i <= 4; $i++){
print(constant("HOUSEHOLD_CHILD".$i).PHP_EOL);
}
The output of the given code will be:
custom_16
custom_14
custom_13
custom_12
DEMO
I need to output a JSON response using PHP5 that looks similar to the following:
{"success": true, "years": [{"yearnumber": 2012},{"yearnumber": 2013},...]}
I have gotten as far as:
$rt = array();
$rt["success"] = true;
$rt["years"] = array();
for ($i=date('Y') ; $i < (date('Y')+21) ; $i++) {
$rt['years'][]= 'yearnumber:'.$i;
}
echo json_encode($rt);
Ofcourse this is not the proper way to achieve my goal - and it obviously doesn't produce the desired results.
I am fairly new to PHP programming and could use a little push here. Thanks.
To get this (The closest valid JSON that would be what I think you want):
{"success":true, "years":[2012,2013,...]}
You can use:
$rt = array();
$rt["success"] = true;
$rt["years"] = array();
for ($i=intval(date('Y')) ; $i < (date('Y')+21) ; $i++) {
$rt['years'][]= $i;
}
echo json_encode($rt);
//{"success":true,"years":[2012,2013,2014,2015,2016,2017,2018,2019,2020,2021,2022,2023,2024,2025,2026,2027,2028,2029,2030,2031,2032]}
For "years": [{"yearnumber": 2012}, {"yearnumber": 2013}]
You can use:
$rt = array();
$rt["success"] = true;
$rt["years"] = array();
for ($i=intval(date('Y')) ; $i < (date('Y')+21) ; $i++) {
$rt['years'][]= array("yearnumber" => $i);
}
echo json_encode($rt);
//{"success":true,"years":[{"yearnumber":2012},{"yearnumber":2013},{"yearnumber":2014},{"yearnumber":2015},{"yearnumber":2016},{"yearnumber":2017},{"yearnumber":2018},{"yearnumber":2019},{"yearnumber":2020},{"yearnumber":2021},{"yearnumber":2022},{"yearnumber":2023},{"yearnumber":2024},{"yearnumber":2025},{"yearnumber":2026},{"yearnumber":2027},{"yearnumber":2028},{"yearnumber":2029},{"yearnumber":2030},{"yearnumber":2031},{"yearnumber":2032}]}
Though it appears redundant to me
This
{"success":true, "years":["yearnumber":2012,"yearnumber":2013,...]}
is not valid JSON. Arrays ([]) can't have keys in them, only values. The best solution (in this scenario) is to just cut they keys since they're all the same anyway (See Esailija's answer)
Another way would be to create an array of objects like this
{"success":true, "years":[{"yearnumber":2012},{"yearnumber":2013},...]}
To achieve that from PHP:
$rt = array();
$rt["success"] = true;
$rt["years"] = array();
for ($i=intval(date('Y')) ; $i < (date('Y')+21) ; $i++) {
$rt['years'][] = array('yearnumber' => $i);
}
echo json_encode($rt);
So I have fields that are generated dynamically in a different page and then their results should posted to story.php page. fields is going to be : *noun1 *noun2 *noun3 and story is going to be : somebody is doing *noun1 etc. What I want to do is to replace *noun1 in the story with the *noun, I have posted from the previous page ( I have *noun1 posted from the previous page ) but the code below is not working :
$fields = $_POST['fields'];
$story = $_POST['story'];
$fieldsArray = split(' ', $fields);
for ($i = 0; $i < count($fieldsArray); $i++) {
${$fieldsArray[$i]} = $_POST[$fieldsArray[$i]];
}
// replace words in story with input
for ($i = 0; $i < count($story); $i++) {
$thisWord = $story[$i];
if ($thisWord[0] == '*')
$story[$i] = ${$thisWord.substring(1)};
}
$tokensArray = split(' ',$tokens);
echo $story;
Your problem is likely that you are trying to echo $story, which I gather is an array. You might have better luck with the following:
$storyString = '';
for ($i = 0; $i < count($story); $i++)
{
$storyString .= $story[i] . ' ';
}
echo $storyString;
echo can't print an array, but you can echo strings to your heart's content.
You almost certainly don't want variable variables (e.g. ${$fieldsArray[$i]}). Also, $thisWord.substring(1) looks like you're trying to invoke a method, but that's not what it does; . is for string concatenation. In PHP, strings aren't objects. Use the substr function to get a substring.
preg_replace_callback can replace all your code, but its use of higher order functions might be too much to get into right now. For example,
function sequence($arr) {
return function() {
static $i=0
$val = $arr[$i++];
$i %= count($arr);
return $val;
}
}
echo preg_replace_callback('/\*\w+/', sequence(array('Dog', 'man')), "*Man bites *dog.");
will produce "Dog bites man." Code sample requires PHP 5.3 for anonymous functions.