I'm trying to accept an unknown number of similarly named POST variables like the following:
foo[bar[0]] = 56
foo[bar[1]] = 43
foo[bar[2]] = ah84
foo[bar[3]] = 92hs
With the rest of my POST data looking like:
foo[baz] = 1432
foo[expected] = 48hf
Some requests may have no foobars, but most will have 1, and some with have 2-4.
Ideally I would like to end with an array: array( 56, 43, ah84, 92hs)
Is there a way to loop through the POST variables not knowing the number of them? I can create the array if I know what to expect, but in this case I have no way of telling what will come across.
Having a look at this example might be a bit of help.
If you know you have an array (with non-sequential indices) and you don't care about the order, the cheapest and easiest fix would be array_values.
In your case, it'd be something like $some_var = array_values($_POST['foo']['bar']).
One possible solution:
$vars = array_unique($your_post_data);
You could get the request header and get the post info from it.
<?php
$header = getallheaders();
$postInfo = explode("&", $header[count($header) - 1]);
for($i = 0; $i < count($postInfo); $i++)
{
$a = explode("=", $postInfo[$i]);
$postInfo[$i] = $a[1];
}
?>
Not tested & may not work but I think you'll get the idea.
Related
I'm a beginner in PHP. I have a text file like this:
Name-Id-Number
Abid-01-80
Sakib-02-76
I can take the data as an array but unable to take it as an associative array. I want to do the following things:
Take the data as an associative array in PHP.
Search Number using ID.
Find out the total of Numbers
I believe I understand what you want, and it's fairly simple. First you need to read the file into a php array. That can be done with something like this:
$filedata = file($filename, FILE_IGNORE_NEW_LINES);
Now build your desired array using a foreach() loop, explode and standard array assignment. Your search requirement is unclear, but in this example, I make the associated array element into an array that is also an associative array with keys for 'id' and 'num'.
As you create the new array, you can compute your sum, as demonstrated.
<?php
$filedata = array('Abid-01-80', 'Sakib-02-76');
$lineArray = array();
$numTotal = 0;
foreach ($filedata as $line) {
$values = explode('-', $line);
$numTotal += $values[2];
$lineArray[$values[0]] = array('id' => $values[1], 'num' => $values[2]);
}
echo "Total: $numTotal\n\n";
var_dump($lineArray);
You can see this code demonstrated here
Updated response:
Keep in mind that notices are not errors. They are notifiying you that your code could be cleaner, but are typically suppressed in production.
The undefined variable notices are coming because you are using:
$var += $var without having initialized $var previously. Note that you were inconsistent in this practice. For example you initialized $numTotal, so you didn't get a notice when you used the same approach to increment it.
Simply add just below $numTotal = 0:
$count = 0;
$countEighty = 0;
Your other notices are occurring most likely due to a blank line or string in your input that does not follow the pattern expected. When explode is executed it is not returning an array with 3 elements, so when you try and reference $values = explode('-', $line); you need to make sure that $line is not an empty string before you process it. You could also add a sanity check like:
enter code hereif (count($values) === 3) { // It's ok to process
Is there a better/shorter way to do this?
Each variable is a MySQL table value that is called. I have a main table and an override table, so call the first table, extract the resulting array, then call the override table and extract those results to override the first extract.
if (isset($Price1)){
$AllPrices[] = $Price1;}
if (isset($Price2)){
$AllPrices[] = $Price2;}
if (isset($Price3)){
$AllPrices[] = $Price3;}
if (isset($Price4)){
$AllPrices[] = $Price4;}
if (isset($SPrice1)){
$AllPrices[] = $SPrice1;}
if (isset($SPrice2)){
$AllPrices[] = $SPrice2;}
if (isset($SPrice3)){
$AllPrices[] = $SPrice3;}
I've done things like this in the past, but I wouldn't recommend it:
$variables = array("Price1", "Price2", "Price3", "Price4", "SPrice1", "SPrice2", "SPrice3");
$AllPrices = array();
foreach ($variables as $variable)
{
if (isset($$variable))
$AllPrices[] = $$variable;
}
See here for more information on how the $$ syntax works in PHP.
But I do agree with the comments to your post... You really should take another look at how you're getting this data. This solution is not ideal in the least.
You can also do like this:
for($i = 1; $i < 4; $i++){
$current = ${'AllPrices'.$i};
isset($current) && array_push($AllPrices, $current);
}
As also posted in above answer, using array of variable names is more efficient.
This structure is not recommended.
Instead of using $price1, $price2, ... use an array - $price[1], $price[2], ... (Do the same for $SPrice).
Then you could use a simple array_merge:
$AllPrices = array_merge($price, $SPrice);
I am doing work where I get data in various formats from various sources. I will end up with something like this:
$dataSource1 = ... ;
$dataSource2 = ... ;
$dataSource3 = ... ;
I need to COMBINE these data sources, all with different field names, into one object, that I can sort according to fields, limit to X number etc.... all for display purposes.
What is the best way to do this? Is there a good php library that does this?
Three possible solutions,
You could always create a database and just use that. (Probably the best thing to do)
Alternatively, you could try attempt to do some polymorphisisng? (cant be made into a verb!)
Finally, you could also include all the other pages into the one you will be displaying from.
(I suggest number 1)
I think the simplest way is using an associative array.
$dataSource1 = ...;
$dataSource2 = ...;
...
$dataSourceN = ...;
$data = array()
$data[0] = $dataSource1;
$data[1] = $dataSource2;
And so on. Just remember that a numeric index array always starts at 0. So the first element would be $data[0].
If you want a more complex bind you can create a multidimensional array. It means you can sort by specific fields. See an example:
$data1 = 'Brazil';
$dataArray = array()
$dataArray[] = array(
'countryId' => 'id',
'countryName' => $data1,
'usersFromThisCountry' => $data1Users
);
Now you can sort $dataArray according to 'countryId','countryName','usersFromThisCountry'.
Let me know if you want more details but:
I have an different number of inserts I need to make based on a POST form data that I created in a loop.
If I were to write it all out it would look like this:
$Scout1=$_POST['ScoutID1'];
$Scout2=$_POST['ScoutID2'];
and it keeps going until it reaches "x" I do have that number stored as
$ScoutCount
(so if the above code would post all the variables I brought over {$ScoutCount=2}
I can't find a way to do:
while (X>0){
$ScoutX=$_POST['ScoutIDX'];
X--;
}
how can I do this?
You might be looking for variable variables
But rather, I would recommend storing the data in an array, as opposed to individual variables. Then in a for loop, it could look like:
$scouts = array();
for ($i = 0; $i < 10; $i++)
{
$scouts[$i] = $_POST['ScoutID' . $i];
}
or something.
instead of having form fields called ScoutID1, ScoutID2 wtc name them
name="ScoutID[]"
then you will have a nice array with work with
//put scoutIDs into Array
$scouts = array();
for ($i = 1; $i <= $ScoutCount; $i++)
{
$scouts[$i] = $_POST['ScoutID' . $i];
}
Thanks - that may have seemed easy but I wasted a day trying to figure it out. thanks from the newbie to Php....
Suppose I have an array of nodes (objects). I need to create a duplicate of this array that I can modify without affecting the source array. But changing the nodes will affect the source nodes. Basically maintaining pointers to the objects instead of duplicating their values.
// node(x, y)
$array[0] = new node(15, 10);
$array[1] = new node(30, -10);
$array[2] = new node(-2, 49);
// Some sort of copy system
$array2 = $array;
// Just to show modification to the array doesn't affect the source array
array_pop($array2);
if (count($array) == count($array2))
echo "Fail";
// Changing the node value should affect the source array
$array2[0]->x = 30;
if ($array2[0]->x == $array[0]->x)
echo "Goal";
What would be the best way to do this?
If you use PHP 5:
Have you run your code? It is already working, no need to change anything. I get:
Goal
when I run it.
Most likely this is because the values of $array are already references.
Read also this question. Although he OP wanted to achieve the opposite, it could be helpful to understand how array copying works in PHP.
Update:
This behaviour, when copying arrays with objects, the reference to the object is copied instead the object itself, was reported as a bug. But no new information on this yet.
If you use PHP 4:
(Why do you still use it?)
You have to do something like:
$array2 = array();
for($i = 0; $i<count($array); $i++) {
$array2[$i] = &$array[$i];
}
it is some time that I don' write PHP code, but does the code
// Some sort of copy system
$array2 = $array;
actually work?
Don't you have to copy each element of the array in a new one?