Assign multiple array to a variable dynamically

Asked

Viewed 278 times

0

Hello, I need to assign several array to a single variable, their value will all be in sequence in this variable. Ex.:

$variavel = $array[0] . $array[1] . $array[2] . $array[3] . $array[4];
echo $variavel

This variable uses it later in an IF to make several comparisons, as I can do this without having to write infinitely assigned array?

2 answers

2

Utilize implode to join/concatenate the values of the arrays

echo implode(array);

See the result: https://3v4l.org/lDbln

About the if, if they are comparisons, it is best to deal directly in the array.

You can use the following functions:

  • in_array - search if a value exists in the array;
  • array_filter - filter the array and return the values passed through the filter;
  • array_reduce - apply a function and reduce an array to a single value. The two previous functions are the most recommended ones, however, if necessary, you can apply a function and return true/false.

Comparing the string directly may not bring consistent results. I won’t go into performance issues, because there’s no need.

  • It worked! Is there any way to generate these array? For example, generate array1, array2, array3 and so on... I know from for but when I try with it, I can’t get the variable that receives the array, outside the scope

  • @Sulivansantos I don’t understand the question. Generate in what way? What do you want to "create"?

  • I will try to explain, each position of the array stores information coming from the database, in the logic I am using here I take the variable that receives the concatenation of all the positions of the array, however for this, I need to express all the positions of the array manually in the code, wanted a way to simplify this, so that if you have for example 50 positions, I do not need to write 50 times, for example: $variavel = $array[0] . $array[1] . $array[2] ... $array[49] . $array[50];

  • @Sulivansantos utilize foreach. foreach($array as $var) { echo $var; }. Run this code and see how it works.

-1

change:

echo $variavel;

for:

echo serealize($varialvel);

or

echo json_encode($variavel);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.