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
Related
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);
}
I've got a string here with names of students (leerlingen) and im trying to follow the exercise here.
The code shows the length of the full string.
Next up would be use a loop to check who has the longest name, but how to implement strlen() in a loop?
// change the string into an array using the explode() function
$sleerlingen = "Kevin,Maarten,Thomas,Mahamad,Dennis,Kim,Joey,Teun,Sven,Tony";
$namen = explode(" ", $sleerlingen);
echo $namen[0];
echo "<br><br>";
//determin the longest name by using a loop
// ask length
$arraylength = strlen($sleerlingen);
sleerlingen = $i;
for ($i = 1; $i <= 10; $i++) {
echo $i;
}
echo $arraylength;
?>
You used bad separator in your explode function, in string there is no space.
This should work (I didn't try it). In foreach loop you check current length with the longest one and if the current is longer, just save it as longest.
<?php
$sleerlingen = "Kevin,Maarten,Thomas,Mahamad,Dennis,Kim,Joey,Teun,Sven,Tony";
$names = explode(',', $sleerlingen);
$longest;
$longest_length = 0;
foreach ($names as $item) {
if (strlen($item) > $longest_length) {
$longest_length = strlen($item);
$longest = $item;
}
}
echo 'Longest name: ' . $longest . ', ' . $longest_length .' chars.';
?>
You can create a custom sort function to sort the array based on the strings length. Then you can easily take the first key in the array.
<?php
$sleerlingen = "Kevin,Maarten,Thomas,Mahamad,Dennis,Kim,Joey,Teun,Sven,Tony";
$namen = explode(",", $sleerlingen); // changed the space to comma, otherwise it won't create an array of the string.
function sortByLength($a,$b){
return strlen($b)-strlen($a);
}
usort($namen,'sortByLength');
echo $namen[0];
?>
Could anyone help me.
I need to return multiple img's, but with this code, only one of two is returning.
What is the solution.
Thank you in advance.
$test = "/claim/img/box.png, /claim/img/box.png";
function test($test)
{
$photo = explode(',', $test);
for ($i = 0; $i < count($photo); $i++)
{
$returnas = "<img src=".$photo[$i].">";
return $returnas;
}
}
This might be a good opportunity to learn about array_map.
function test($test) {
return implode("",array_map(function($img) {
return "<img src='".trim($img)."' />";
},explode(",",$test)));
}
Many functions make writing code a lot simpler, and it's also faster because it uses lower-level code.
While we're on the subject of learning things, PHP 5.5 gives us generators. You could potentially use one here. For example:
function test($test) {
$pieces = explode(",",$test);
foreach($pieces as $img) {
yield "<img src='".trim($img)."' />";
}
}
That yield is where the magic happens. This makes your function behave like a generator. You can then do this:
$images = test($test);
foreach($images as $image) echo $image;
Personally, I think this generator solution is a lot cleaner than the array_map one I gave earlier, which in turn is tidier than manually iterating.
Modify your code that way
function test($test)
{
$returnas = '';
$photo = explode(',', $test);
for ($i = 0; $i < count($photo); $i++)
{
$returnas .= "<img src=".$photo[$i].">";
}
return $returnas;
}
Your code didn't work since you were returning inside the loop immediatly. Every programming language support "only a return for call". In my solution you're appendig a string that has an img tag each time you enter the loop and return it after every photo is "passed" into the loop
You could even use the foreach() construct, of course
Bonus answer
If you don't know the difference between ...
for ($i = 0; $i < count($photo); $i++)
and
for ($i = 0, $count = count($photo); $i < $<; $i++)
Well, in first case you'll evaluate count($photo) every single time the for is called whereas the second time, it is evaluated only once.
This could be used for optimization porpuses (even if php, internally, stores the length of an array so it is accesible in O(1))
The function breaks after the first return statement. You need to save what you want to return in some structure, an array eg, and return this.
function test($test)
{
$result = array();
$photo = explode(',', $test);
for ($i = 0; $i < count($photo); $i++)
{
$returnas = "<img src=".$photo[$i].">";
$result[] = $returnas;
}
return $result;
}
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.