I just started learning PHP and I am having some difficulties with some of the coding.
Hopefully, someone could help me a little.
I'm using this:
if(!empty($_POST['yyy'])) {
foreach($_POST['yyy'] as $a1) {
echo " $a1";}}
The echo will write several results of $a1 depending on how many were selected in the form.
What I want is to save those results to some values so I can add them in MySQL.
Something like this:
if(!empty($_POST['yyy']))
{
foreach($_POST['yyy'] as $a1)
{
echo " $a1"; where $a1 will create a $result1,$result2,$result3(for each isset)
}
}
Then if I use:
echo "$result2";
it will give me the second result.
Not clear whether you are asking about this kind of result or not. But you can use an array to store each values inside the foreach loop.
var data=[];// define an array to access outside of if statement later..
if(!empty($_POST['yyy'])) {
foreach($_POST['yyy'] as $a1){
data[]=$a1;
//or can use array_push() method
array_push(data,$a1);
}
}
/*this will give the second result(because array indexing starts from 0. So to get third result
use data[2])*/
echo data[1];
Furthermore by echoing quoted variable will not give the value of that variable but gives a string literal.
echo "$result2" //output---> $result
Related
i have an array result. i want to print 2 rows(product data) in first page.
next 2 rows in second page and so on. if anybody knows this,please help me to solve it
my array
$data['product_list']
foreach($data['product_list'] as $dat)
{
echo $dat->prd_id;
echo $dat->prd_name;
}
You are doing a foreach loop on an associative array and then trying to access the the contents as objects by using ->. I can only given assumption of what you might be doing. If your array is already populated with a name and id like you have described in your foreach loop this is how you would access the contents in the loop:
foreach($data['product_list'] as $dat)
{
echo $dat['prd_id'];
echo $dat['prd_name'];
}
That is how you would print out the contents providing you had the data stored in your array like so:
$data['product_list'][0] = array('prd_id'=>'id0','prd_name'=>'name0');
$data['product_list'][1] = array('prd_id'=>'id1','prd_name'=>'name1');
$data['product_list'][2] = array('prd_id'=>'id2','prd_name'=>'name2');
Better you try with array_slice();
<?php
$a=array("red","green","blue","yellow","brown");
print_r(array_slice($a,2));
?>
I am attempting to use a for loop or for each loop to push the values from a get query to another variable. May I have some help with this approach?
Ok here is where I am:
for ($i = 0 ; i < $_GET['delete']; i++) {
$_jid [] = $_GET['delete'];
}
You don't actually need a loop here. If $_jid already is an array containing some values, consider just merging it with $_GET['delete'].
if (is_array($_jid)) {
$_jid = array_merge($_jid, $_GET['delete']);
}
If $_jid is not an array and doesn't exist except as a container for $_GET['delete'] you do can just assign the array. There is no need to loop at all.
$_jid = $_GET['delete'];
Of course in that case, you don't even need to copy it. You can just use $_GET['delete'] directly, in any context you planned to read from $_jid.
Update:
If the contents of $_GET['delete'] are originally 923,936, that is not an array to begin with, but rather a string. If you want an array out of it, you need to explode() it on assignment:
$_jid = explode(',', $_GET['delete']);
But if you intend to implode() it in the end anyway, there's obviously no need to do that. You already have exactly the comma-delimited string you want.
As you can see if you do a var_dump($_GET), the variable $_GET is a hashmap.
You can easily use a foreach loop to look through every member of it :
foreach($_GET as $get) // $get will successively take the values of $_GET
{
echo $get."<br />\n"; // We print these values
}
The code above will print the value of the $_GET members (you can try it with a blank page and dull $_GET values, as "http://yoursite.usa/?get1=stuff&get2=morestuff")
Instead of a echo, you can put the $_GET values into an array (or other variables) :
$array = array(); // Creating an empty array
$i = 0; // Counter
foreach($_GET as $get)
{
$array[$i] = $get; // Each $_GET value is store in a $array slot
$i++;
}
In PHP, foreach is quite useful and very easy to use.
However, you can't use a for for $_GET because it's a hashmap, not an array (in fact, you can, but it's much more complicated).
Hope I helped
foreach loop only repeating the last element of the arary?
java Script Code :
<?php foreach($_REQUEST["itemprice"] as $itemprice)
{
?>
+ "&itemname_price[]=<?php echo $itemname?>_price=" + <?=$itemname?>_price.value
<?php
}
?>
Code to request that data
$items_price = array();
foreach($_REQUEST['itemname_price'] as $itemname_pric) {
$items_price[]=$itemname_pric;
}
print_r($items_price);
foreach is used to get the values from an array, and what you are trying here is to get data from a specific array key. I guess that's why you are getting a single value. You can refer to
http://php.net/manual/en/control-structures.foreach.php to get the exact use of foreach.
Let me know if you have anything to know.
Here's a test jason feed
{"MEMBERS":[{"NAME":"Joe Bob","PET":["DOG"]}, {"NAME":"Jack Wu","PET":["CAT","DOG","FISH"]}, {"NAME":"Nancy Frank","PET":["FISH"]}]}
What I'm attempting to do is extract data if PET contains CAT or FISH or both. Another user suggested a filter as such:
$filter = array('CAT', 'FISH');
// curl gets the json data (this part works fine but is not shown for brevity)
$JSONarray=json_decode($JSONdata,true);
foreach($JSONarray['MEMBERS'] as $p) {
if (in_array($p['PET'], $filter)) {
echo $p['NAME'] . '</br>';
}
}
But it's not returning anything.
Note: edited based on comments below
Use strings to access the array and not uninitialized constants.
$p['PET'] is an array. You have to use some other method to compare it against $filter, e.g. array_intersect:
foreach($JSONarray['MEMBERS'] as $p) {
$diff = array_intersect($filter, $p['PET']);
if (!empty($diff)) {
echo $p['NAME'].'</br>';
}
}
DEMO
It should work like this:
foreach($JSONarray['MEMBERS'] as $p) {
if (array_diff($p['PET'], $filter) != $p['PET']) {
echo $p['NAME'].'</br>';
}
}
Remember to always use quotes when you are trying to access an element of an associative array. Without quotes, PHP tries to interpret it as a constant (throwing a Notice on failure). So instead of $a[index] do $a['index']. Please also see Why is $foo[bar] wrong?
In your code, $p['PET'] will be an array of pet names, not one pet name. Testing with in_array() won't be successful, because it will try to find the whole array in $filter. In my code example, I used array_diff() which will find the difference between the two arrays, then I compare it to the original array. If they match, the $filter pets were not found.
First, you need to use quotes on your array keys:
$JSONarray['MEMBERS']
$p['PET']
$p['NAME']
Secondly, you can't use in_array as it assumes 'needle' to be the array('CAT', 'FISH') and not any one of it's values.
(The parameter order was also the other way around)
Here's a method using array_intersect:
foreach($JSONarray['MEMBERS'] as $p) {
$test = array_intersect($filter, $p['PET']);
if (count($test)>0) {
print( $p['NAME'].'</br>' );
}
}
When sending data from a form to a second page, the value of the session is always with the name "Array" insteed of the expected number.
The data should get displayed in a table, but insteed of example 1, 2, 3 , 4 i get : Array, Array, Array.
(A 2-Dimensional Table is used)
Is the following code below a proper way to "call" upon the stored values on the 2nd page from the array ?
$test1 = $_SESSION["table"][0];
$test2 = $_SESSION["table"][1];
$test3 = $_SESSION["table"][2];
$test4 = $_SESSION["table"][3];
$test5 = $_SESSION["table"][4];
What exactly is this, and how can i fix this?
Is it some sort of override that needs to happen?
Best Regards.
You don't need any sort of override. The script is printing "Array" rather than a value, because you're trying to print to the screen a whole array, rather than a value within an array for example:
$some_array = array('0','1','2','3');
echo $some_array; //this will print out "Array"
echo $some_array[0]; //this will print "0"
print_r($some_array); //this will list all values within the array. Try it out!
print_r() is not useful for production code, because its ugly; however, for testing purposes it can keep you from pulling your hair out over nested arrays.
It's perfectly fine to access elements in your array by index: $some_array[2]
if you want it in a table you might do something like this:
<table>
<tr>
for($i = 0 ; $i < count($some_array) ; $i++) {
echo '<td>'.$some_array[$i].'</td>';
}
</tr>
</table>
As noted, try
echo "<pre>";
print_r($_SESSION);
echo "</pre>";
That should show you what's in the session array.
A 2-dimensional table is just an array of arrays.
So, by pulling out $_SESSION["table"][0], you're pulling out an array that represents the first row of the table.
If you want a specific value from that table, you need to pass the second index, too. i.e. $_SESSION["table"][0][0]
Or you could just be lazy and do $table = $_SESSION["table"]; at which point $table would be your normal table again.
A nice way ...
<?php
foreach ($_SESSION as $key => $value) {
echo $key . " => " . $value . "<br>";
}
?>