dynamically creating array in php - 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;
}
}

Related

How to replace array_value?

$arr = ["250","250","500","500","250"];
Here is my $arr array. I want to replace 300 instead of 500.
Sample:
["250","250","300","300","250"]; //Output
Here is my code
$length = sizeof($arr);
for($i = 0; $i < $length; $i++)
{
if($arr[$i] <= 300)
{
}
else
{
$replace = array($i => "300");
array_replace($arr, $replace);
}
}
You should use the str_replace() function, that allows you to replace a value with another one in both strings and arrays.
In your case it would be:
$arr = str_replace("500","300",$arr);
you could use array_replace(), but it works not by value, rather by position, and array_replace() returns a new array rather than mutating the original one.
you could modify the else part of your code like below, since you were not using the modified array;
....
....
else
{
$replace = array($i => "300");
$arr2 = array_replace($arr, $replace);
var_dump($arr2);//this holds the replaced array
}

How to stop loop string inside PHP loop with array

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.', ';

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";
}
?>

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)

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?

Categories