How to stop loop string inside PHP loop with array - php

I'm trying to stop $implode_demographics inside for loop below.
For example, if I use echo $implode_demographics inside loop, then I will get:
a01a01,a02a01,a02,a03a01,a02,a03,a04a01,a02,a03,a04,a05a01,a02,a03,a04,a05,a06a01,a02,a03,a04,a05,a06,a07a01,a02,a03,a04,a05,a06,a07,a08a01,a02,a03,a04,a05,a06,a07,a08,a09a01,a02,a03,a04,a05,a06,a07,a08,a09,a10a01,a02,a03,a04,a05,a06,a07,a08,a09,a10,a11a01,a02,a03,a04,a05,a06,a07,a08,a09,a10,a11,b01a01,a02,a03,a04,a05,a06,a07,a08,a09,a10,a11,b01,b02a01,a02,a....
But If I use this string outside, then output works.
a01,a02,a03,a04,a05,a06,a07,a08,a09,a10,a11,b01,b02,b03,c01,c02,c03,c04,c05,c06,c07,c08,c09,c10,c11,c12,c13
Online PHP test
So, how I can echo $implode_demographics inside for loop to get same result?
$a_l_demographics = [11,3,13];
$a_p_demographics = ['a','b','c'];
$a_r_demographics = [];
$c_demographics_values = array();
$a_c_demographics = min(count($a_l_demographics), count($a_p_demographics));
for ($i = 0; $i < $a_c_demographics; $i++) {
for ($j = 1; $j <= $a_l_demographics[$i]; $j++) {
$a_r_demographics[] = $a_p_demographics[$i] . str_pad($j, 2, 0, STR_PAD_LEFT);
$implode_demographics = implode($a_r_demographics, ',');
// this won't work
echo $implode_demographics;
}
}
// this works
// echo $implode_demographics;

It doesn't works because you implode the same array again and again after you add data in it.
So in your first echo you have only a01, then you implode after with a01 and a02 value, etc.
Try to add echo $implode_demographics . "\n"; and you will see that you have one var, then two, then three, etc. see example here : https://3v4l.org/WrCgJ
So if you want to echo each value INSIDE, just do :
<?php
$a_l_demographics = [11,3,13];
$a_p_demographics = ['a','b','c'];
$a_r_demographics = [];
$c_demographics_values = array();
$a_c_demographics = min(count($a_l_demographics), count($a_p_demographics));
for ($i = 0; $i < $a_c_demographics; $i++) {
for ($j = 1; $j <= $a_l_demographics[$i]; $j++) {
$a_r_demographics[] = $a_p_demographics[$i] . str_pad($j, 2, 0, STR_PAD_LEFT);
$implode_demographics = implode($a_r_demographics, ',');
// You echo only the last value
echo $a_p_demographics[$i] . str_pad($j, 2, 0, STR_PAD_LEFT);
// If it's not the last loop : you add a `,`
if (!($i == ($a_c_demographics - 1) && $j == $a_l_demographics[$i]))
echo ",";
}
}
This way you will echo only the LAST value each time and not all the value from the beginning each time, the output is :
a01,a02,a03,a04,a05,a06,a07,a08,a09,a10,a11,b01,b02,b03,c01,c02,c03,c04,c05,c06,c07,c08,c09,c10,c11,c12,c13
See code here : https://3v4l.org/MEnGe

In fact it's work, you have a problem with the implode. Implode d'ont put the glue (,) to the last value !
try this.
$implode_demographics = implode($a_r_demographics, ',');
echo $implode_demographics.', ';

Related

get a set of values from an array

i have a set of arrays:
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
what i want to do is to get a set of $data array from each number of $nums array,
the output must be:
output:
2=11,22
3=33,44,55
1=66
what i tried so far is to slice the array and remove the sliced values from an array but i didn't get the correct output.
for ($i=0; $i < count($nums); $i++) {
$a = array_slice($data,0,$nums[$i]);
for ($x=0; $x < $nums[$i]; $x++) {
unset($data[0]);
}
}
Another alternative is to use another flavor array_splice, it basically takes the array based on the offset that you inputted. It already takes care of the unsetting part since it already removes the portion that you selected.
$out = array();
foreach ($nums as $n) {
$remove = array_splice($data, 0, $n);
$out[] = $remove;
echo $n . '=' . implode(',', $remove), "\n";
}
// since nums has 2, 3, 1, what it does is, each iteration, take 2, take 3, take 1
Sample Output
Also you could do an alternative and have no function usage at all. You'd need another loop though, just save / record the last index so that you know where to start the next num extraction:
$last = 0; // recorder
$cnt = count($data);
for ($i = 0; $i < count($nums); $i++) {
$n = $nums[$i];
echo $n . '=';
for ($h = 0; $h < $n; $h++) {
echo $data[$last] . ', ';
$last++;
}
echo "\n";
}
You can array_shift to remove the first element.
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
foreach( $nums as $num ){
$t = array();
for ( $x = $num; $x>0; $x-- ) $t[] = array_shift($data);
echo $num . " = " . implode(",",$t) . "<br />";
}
This will result to:
2 = 11,22
3 = 33,44,55
1 = 66
This is the easiest and the simplest way,
<?php
$nums = array(2,3,1);
$data = array(11,22,33,44,55,66);
$startingPoint = 0;
echo "output:"."\n";
foreach($nums as $num){
$sliced_array = array_slice($data, $startingPoint, $num);
$startingPoint = $num;
echo $num."=".implode(",", $sliced_array)."\n";
}
?>

php code to increment month inside for loop

i have starting date ..
i need to add months in starting date inside for loop
for ex -
startingdate = 25-03-2015
and my loop runs two time then it generate like below
25-04-2015
25-05-2015
thats it...
$startingdate = $_POST['startingdate'];
$dates = date("d-m-Y", strtotime($startingdate . " +" . " 1MONTHS -1 DAYS"));
for ($i = 0; $i <= 2; $i++)
{
$coupondate = $dates;
}
If your results are returned with commas separting. Then use explode() to return an array of values. Then using max() and min() in php you can set your lower and upper limits to loop through.
But if you're getting all the results anyway, explode() should do the trick, then just loop through them.
$result = "100,101,102,103";
$arr = explode(",", $result);
foreach ($arr as $number) {
echo $number;
}
Or with min / max:
$result = "100,101,102,103";
$arr = explode(",", $result);
$min = min($arr);
$max = max($arr);
for ($i = $min; $i <= $max; $i++) {
echo $i;
}
Take a look at
min() and
max()
$points=array(500,501,502,503,504,505,506);
$min=min($points);
$max=max($points);
for($i=$min;$i<$max+1;++$i{
//do something
}
If your data is stored lower to upper :
$text = '500,501,502,503,504,505,506';
$explode = explode(',',$text);
$index = count($explode)-1;
for ($i=$explode[0]; $i<=$explode[$index]; $i++)
{
echo $i;
}
If order can change, add :
sort($explode);
Try this :
//after connected with a database
$data = (explode(",", $rows["points"]));
for ($i=min($data); $i<=max($data); $i++)
{
}
Note : If the separation between words is ', ' (a comma and space) then change with this :
$data = (explode(", ", $rows["points"]));

PHP variables in a complex way

<?php
$td = date("d");
for ($i = 1; $i <= $td; $i++)
{
$num18 = count($this->numbermonth18);
echo "['1'," . $num18 . "],";
}
The above code will display the output like, ['1',12],['1',12],['1',12],['1',12],['1',12],['1',12],['1',12],['1',12],['1',12],['1',12],['1',12],['1',12],['1',12],['1',12],['1',12],['1',12],['1',12],['1',12],['1',12],['1',12],['1',12],['1',12],['1',12],['1',12],['1',12],['1',12],['1',12],['1',12],['1',12],['1',12],.
I need to replace the 18 with $i value in the above code. How can I use $i instead of 18 in the for loop to display all the values of $this->numbermonth1, $this->numbermonth2, $this->numbermonth3 etc. and print the array?
You could do with:
for($i=1;$i<=$td;$i++)
{
$num=count($this->{'numbermonth'.$i});
echo "['1',".$num."],";
}

php variable after a variable in for loop

I need a way to do this
for($i=1;$i<=10;$i++){
$id$i = "example" . $i;
}
notice the second line has $id$i
so for the first loop $id1 will equal example1
in the second loop $id2 will equal example2
and so on...
Thank you very much!
You can use variable variable names to do this; however, it's probably much more convenient if you just used an array:
for($i = 1, $i <= 10, $i++) {
$id[] = "example" . $i;
}
You can convert a string into a variable (the name of the variable), if you put another $ in front of it:
$str = "number";
$number = 5;
$$str = 8;
echo $number; // will output 8
So in your example, you could do it like that:
for($i = 1; $i <= 10; $i++) {
$str_var = "id".$i;
$$str_var = "example".$i;
}
It would be much better to use an array, but you could do this:
for($i=1; $i<=10; $i++){
$var ="id$i";
$$var = "example" . $i;
}
Here's what I would recommend doing instead:
$ids = array;
for($i = 1; $i <= 10; $i++) {
$ids[$i] = "example" . $i;
}
You could create an array of size $i with a name of $id, and insert each element into a different index.
for($i=1;$i<=10;$i++){
$id[$i] = "example" . $i;
}
$var = array();
for($i=1; $i<=10; $i++) {
$var['id' . $i] = 'example' . $i;
}
extract($var, EXTR_SKIP);
unset($var);
but why not use a simple array?

dynamically creating array in php

I am trying to create arrays dynamically and then populate them by constructing array Names using variable but I am getting the following warnings
Warning: in_array() expects parameter 2 to be array, null given
Warning: array_push() expects parameter 1 to be array, null given
For single array this method worked but for array of arrays this is not working. How should this be done?
<?php
for ($i = 1; $i <= 23; ++$i)
{
$word_list[$i] = array("1");
}
for ($i = 1; $i <= 23; ++$i)
{
$word = "abc";
$arrayName = "word_list[" . $i . "]";
if(!in_array($word, ${$arrayName}))
{
array_push($$arrayName , $word);
}
}
?>
Why are even trying to put array name in a variable and then de-reference that name? Why not just do this:
for ($i = 1; $i <= 23; ++$i)
{
$word = "abc";
$arrayName = "word_list[" . $i . "]";
if(!in_array($word, $word_list[$i]))
{
array_push($word_list[$i] , $word);
}
}
You get the first warning because your $arrayName variable is not actually an array, you made it into a string.
So instead of:
$arrayName = "word_list[" . $i . "]";
You should have this:
$arrayName = $word_list[$i];
You get your second warning because your first parameter is not an array.
So instead of:
array_push($$arrayName , $word);
You should have this:
array_push($arrayName , $word);
If you make these changes you will get an array that looks like this in the end:
$wordlist = array( array("1", "abc"), array("1", "abc"), ... ); // repeated 23 times
And in the for loop, you are accessing the array the wrong way
Here is your corrected code
for ($i = 1; $i <= 23; ++$i)
{
$word = "abc";
$arrayName = $word_list[$i];
if(!in_array($word, $arrayName))
{
array_push($arrayName , $word);
$word_list[$i] = $arrayName;
}
}

Categories