How to implode many available to one available using loop for? - php

How to implode many available to one available using loop for ?
i have many available like
$var_1 = one;
$var_2 = two;
$var_3 = three;
$var_4 = four;
$var_5 = five;
$var_6 = six;
$var_7 = seven;
$var_8 = eight;
$var_9 = nine;
$var_10 = ten;
$var_11 = eleven;
and then i want to implode to one available
$all_data = one,two,three,four,five,six,seven,eight,nine,ten,eleven,
but i want to using loop for like this
for ( $i=1;$i<12;$i++ )
{
$all_data = ${var_$i}.",";
}
how can i do ? thank you for every comment ^^

$all_data = implode(',', array($var_1, $var_2, ..., $var_11));
Any time you find yourself creating a bunch of variables with numeric names like this, say to yourself: "I really should be using an array". There's almost never a good reason for this type of programming.
For the for loop you're trying to write, see the PHP documentation on Variable Variables.
$all_data = '';
for ($i = 1; $i < 12; $i++) {
$all_data .= ${'var_'.$i} . ',';
}

Related

is it posible to auto increment variable name after a while loop?

I need to create a php file with a hundred variables, which are all identical except for their id.
PHP Code
$var1 = get_input('myvar1');
$var2 = get_input('myvar2');
$var3 = get_input('myvar3');
$var4 = get_input('myvar4');
...
$var30 = get_input('myvar30');
I wonder if it is possible to create only one line as a model, and is replicated 30 times?
I think you are looking after something like this :
$vars = [];
for($i = 1; $i <= 30; $i++) {
$vars[] = get_input('myvar' . $i);
}
this is a job for arrays
$var = array_fill(1, 30, 'myvar');
use the array key as your "id"
Why bother with arrays when you can create the variables like so. The variables names are also set dynamically just like the values.
for ($i = 1; $i <= 100; $i++) {
${'var' . $i} = get_input('myvar' . $i);
}

PHP - Stop need to create hundreds of variables

I'm writing a script and it seems like a bit of a ballache so I came on SO to ask for a little help making my script more dynamic so I create a better version of what I'm doing. I've read into variable variables but I'm still stuck on how I'd use them.
I'll obviously shorten this down but my current script is:
$a0 = $tags['items'][0]['snippet']['tags'];
$a1 = $tags['items'][1]['snippet']['tags'];
$a2 = $tags['items'][2]['snippet']['tags'];
if (!is_array($a0)) { $a0 = array(); }
if (!is_array($a1)) { $a1 = array(); }
if (!is_array($a2)) { $a2 = array(); }
$a0 = array_map('strtolower', $a0);
$a1 = array_map('strtolower', $a1);
$a2 = array_map('strtolower', $a2);
array_count_values(array_merge($a0,$a1,$a2));
I'm looking for a way to dynamically create the variables (For example using an index in a while loop rather than creating these variables uniquely. This obviously is fine on a small scale, but i've currently done 50 of these for each and it's causing serious time problems. Any help is much appreciated
Treat the whole $tags variable as an array and you can do this, similar to the strtolower array_map you have already:
$tagItems = [];
foreach($tags['items'] as $item) {
if (!$item['snippet']['tags'] || !is_array($item['snippet']['tags'])) {
continue;
}
foreach($item['snippet']['tags'] as $tag) {
$tag = strtolower($tag);
if (!isset($tagItems[$tag])) {
$tagItems[$tag] = 0;
}
$tagItems[$tag]++;
}
}
As #FranzGleichmann says, try not to use variable variables, which are a smell and potential security risk, but instead rethink how you want to approach the problem.
You should be able to produce the same output that you get from array_count_values with a nested foreach loop.
foreach ($tags['items'] as $x) { // loop over the list of items
foreach ($x['snippet']['tags'] as $tag) { // loop over the tags from each item
$tag = strtolower($tag);
if (!isset($counts[$tag])) $counts[$tag] = 0;
$counts[$tag]++; // increment the tag count
}
}
No need to create 100 variables. That would cause a headache. Instead, use a simple loop function.
$b = array();
for ($n=1; $n<=100; $n++) {
$a = $tags['items']["$n"]['snippet']['tags'];
if (!is_array($a)) { $a = array(); }
$a = array_map('strtolower', $a);
array_count_values(array_merge($b,$a));
}
I hope it works! Have a nice coding
I would write this in a comment but i will a long one,
Variable Variable, is simply the value of the original var assigned as a var name, which means:
$my_1st_var = 'im_1st';
//use $$
$$my_1st_var = 'im_2nd'; //that is the same of $im_1st='im_2nd';
//results
echo $my_1st_var; // >>> im_1st
echo $im_1st; // >>> im_2nd
that means i created a new var and called it the value of the 1st var which is im_1st and that makes the variable name is $im_1st
also you can set multiple values as a var name:
$var0 = 'a';
$var1 = 'b';
$var2 = 'c';
$var3 = '3';
//we can do this
${$var0.$var1} = 'new var 1'; //same as: $ab = 'new var 1';
${$var1.$var2.$var3} = 'im the newest'; //same as: $bc3 = 'im the newest';
//set a var value + text
${$var0.'4'.$var1} = 'new?'; //same as: $a4b = 'new?';
also $GOLBALS[]; is some kind of $$
hope it helps you understanding what is hard for you about $$ ;)
Alright so dynamically creating variables is easy is a script language like PHP.
You could make $a an array, and instead of $a0, $a1, ... use $a[$i] where $i goes from 0 to 50 or more.
Or you could use this nice funky syntax: ${'a'.$i}. For example:
$i = 0;
${'a'.$i} = 'foobar';
echo $a0; // will output foobar
However you shouldn't do any of this.
What you should do is think about what you are trying to achieve and come up with a different algorithm that doesn't require dynamically named variables.
In this case, something like this looks like it would do the job:
$result = [];
foreach ( $tags['items'] as $item ) {
if ( is_array($item['snippet']['tags']) ) {
$result = array_merge($result, array_map('strtolower',$item));
}
}
array_count_values($result);
This is obviously not tested and from the top of my head, but I hope you get the idea. (EDIT: or check the other answers with similarly rewritten algorithms)

Explode and then merge arrays

I have two strings, one containing names separated by commas and the other containing email addresses separated by commas.
I now want my end result to replicate the behaviour as if I had gotten those values from the database with a:
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo $row['name'].'<br />'.$row['email'];
}
So I have for example these strings:
email1#domain.com,email2#domain.com,email3#domain.com
and
name1,name2,name3
And can then explode these into value arrays. Now, after exploding them,
I want to be able to make a loop where in each loop I can get $name[0] and $email[0] together, and $name[1] and $email[1] together, etc.
How can I merge the two arrays (after exploding them) and get the data for each datapair (name and email) in a loop?
So if I understood you right, you are converting your strings (lets call them email, and name) too two arrays (lets call them arrEmail, and arrName) and now you want to get a array with the merged datasets.(creating the arrays should be easy if not check this out: manual for php explode function)
If so I would create a for loop based on the length of your two arrays. In the loop I would extract value i of arrEmail and arrName, and put the information into an two-dimensional array. Maybe something like this:
It should work but I didn't test it for ages so if not leave me a comment.
<?php
$arrEmail = array();
$arrName = array();
$arrGoal;
$arrLength = count($arrName);
//creating two-dimensional Array
for($i = 0; $i < $arrLength; $i++){
$arrGoal[$i] = array($arrName[$i], $arrEmail[$i]);
//should look something like this ((name, email),(name, email)…)
}
$arrGoalLength = count($arrGoal);
//accessing Array
//1. dimension
for($i = 0; $i < $arrGoalLength; $i++){
//2. dimension
//Variables should be global (but aren't)
$newName = $arrGoal[$i][0];
$newEmail = $arrGoal[$i][1];
}
?>
I think you want something like this:
$output = array();
for ($i = 0; $i < count($names); $i++) {
$output[] = $names[$i] . ' ' . $emails[$i];
}
print_R($output);
$emails = 'email1#domain.com,email2#domain.com,email3#domain.com';
$emails = explode(',', $emails);
$names = 'name1,name2,name3';
$names = explode(',', $names);
and you can use array_combine() as follow :
$combined = array_combine($names, $emails);
foreach($combined as $name => $email){
echo $name, ' : ', $email, '<br/>';
}
I think you should use the built in explode function wich will allow you to turn a string to an array by spliting it using a delimiter (comma) :
$names = explode(",",$row['name']);
$email = explode(",",$row['email']);
for merging them you should use something like this
$Array = array();
for ($j = 0; $j < count($names); $j++) {
$Array[] = [$names[$j],$email[$j]];
}
This is kind a related with your question, but only if you like to access the value by a key(e.g. access the name by email provided):
<?php
$emails = 'email1#gmail.com,email2#gmail.com,email3#gmail.com';
$names = 'name1,name2,name3';
$arrayEmails = explode(',',$emails);
$arrayNames = explode(',',$names);
$result = array_combine( $arrayEmails, $arrayNames);
print_r($result);
?>

Change the value in one array based on the key of an associative array using PHP

I hope my question adequately describes what I'm after...
Here is the situation. I have the following arrays with values.
categories['t-shirts'] = 10
categories['shorts'] = 11
...
clothing[0] = 't-shirts'
clothing[1] = 'shorts'
...
I want to replace the values in the clothing array (t-shirts, shorts) with the number that matches it from the categories array.
Cheers
foreach($clothing as $key => $val){
if(isset($categories[$val])){
$clothing[$key] = $categories[$val];
}
}
Codepad Example
You can use simple php
categories[clothing[0]] = "some value"
From your question, it looks like
$newArray=array_keys($originalArray);
should do the trick.
$count = count($clothing);
for($i=0; $i<$count; $i++)
$clothing[$i] = (array_key_exists($clothing[$i], $categories))
? $categories[$clothing[$i]] : 0;
for setting the $clothings without any count to 0
$categories = array();
$categories['t-shirts'] = 10;
$categories['shorts'] = 11;
$clothing = array();
$clothing[0] = 't-shirts';
$clothing[1] = 'shorts';
array_walk($clothing,
function(&$value) use($categories) {
if (isset($categories[$value]))
$value = $categories[$value];
}
);
var_dump($clothing);

Comparing an array against itself

I am currently a bit stuck in finding out how to compare these variables against eachother, I have 24 dropdown selections with 24 options to choose from within each one, I then post them to the PHP page. What is the easiest, most efficient way of comparing each of these values against each other to check that each option that is chose is different from each other as none of the 24 options can be the same. I know that an array is the way forward with this, just not sure on how to compare them.
Any help is much appreciated.
$id = $_POST[trackid];
$pos1 = $_POST[pos1];
$pos2 = $_POST[pos2];
$pos3 = $_POST[pos3];
$pos4 = $_POST[pos4];
$pos5 = $_POST[pos5];
$pos6 = $_POST[pos6];
$pos7 = $_POST[pos7];
$pos8 = $_POST[pos8];
$pos9 = $_POST[pos9];
$pos10 = $_POST[pos10];
$pos11 = $_POST[pos11];
$pos12 = $_POST[pos12];
$pos13 = $_POST[pos13];
$pos14 = $_POST[pos14];
$pos15 = $_POST[pos15];
$pos16 = $_POST[pos16];
$pos17 = $_POST[pos17];
$pos18 = $_POST[pos18];
$pos19 = $_POST[pos19];
$pos20 = $_POST[pos20];
$pos21 = $_POST[pos21];
$pos22 = $_POST[pos22];
$pos23 = $_POST[pos23];
$pos24 = $_POST[pos24];
Given an array you could try array_unique function
count($original_array) != count(array_unique($original_array))
Alternative solution with array_count_values
count(array_count_values($original_array)) = count($original_array)
There are lot of way to do that (e.g. a for loop), it just depends from your exact needs.
Firstly, you should be adding quotes around your array indices rather than using barewords which should be raising warnings:
$pos1 = $_POST['pos1'];
To copy the pos* values out of $_POST, you should use a loop:
$pos = array();
for ($i = 1; $i <= 24; ++$i) {
$pos["pos$i"] = $_POST["pos$i"];
}
To make sure there are no duplicates, use array_unique and see if the two arrays have the same length:
if (count(array_unique($pos)) == count($pos)) {
# pos contains no duplicates
}
Just do an array_unique on it. First you'll need to put those POST vars into an array instead of splitting them up.
$pos = array();
for ($i = 1; $i <= 24; $i++)
{
$pos["pos$i"] = $_POST["pos$i"];
}
$unique = array_unique($pos);
if (count($unique) == 24)
{
// all good!
}
else
{
// bad!
}
can you more explicit? if none of them can be the same, than what is the problem?
considering that you actually can select the same option more than once or you just want to protect from attacks, than you can put them into an array, and then use the array_unique function.

Categories