Incremented $_COOKIE[array] not working? - php

I am using a $_COOKIE[array] in order to save data for a single input. This input will only submit if the user entered the same value twice. For instance, if they submitted apple, then orange, then banana, then apple, the form would submit on the second appearance of "apple".
I read [this tutorial](
http://phpprogramming.wordpress.com/2007/03/06/php-cookies-tutorial-and-examples/).
for ($i = 1; $i < 10; $i++) {
if (!isset($_COOKIE[$i])) {
setcookie("query" . [$i],$query,time()+604800,"/");
break1;
}
}
foreach ($_COOKIE["query"] as $key => $value) {
echo "$key:$value";
}
I believe it might be a syntax error since I get:
Warning: Invalid argument supplied for foreach()
If you know a better way (can't be mySQL), then please let me know!

$_COOKIE["query"] is not an array, that's whats producing the error.

$_COOKIE['query'] can not store an array. This is also why you get an error when you try to use it in the foreach. You could serialize your array before saving it though. Something like this
$array = array();
for ($i = 1; $i < 10; $i++) {
$array[] = $i;
}
setcookie("query",urlencode(serialize($array)),time()+604800,"/");
$query = unserialize(urldecode($_COOKIE['query']));
foreach ($query as $key => $value) {
echo "$key:$value";
}
also have a look at this post update cookie value in php for the expalanation why the urlencode / urldecode is used

Related

How to pas array in loop in php?

I am facing the problem is that I want to display all image by using array and loop,it is not showing all image ,it does show only one image.Here is my code
if($objResult['Image_Type'] == '01') {
$img11 = array($objResult['Image_Name']);
for ($i=0; $i < count($img11[$i]); $i++) {
$im_mouths = array($img11[$i]);
}
}
here is in the database to extract out all image
the out put is showing only one image by using this code
<? echo $im_mouths[0].'11111'.'<br>';?>
<? echo $im_mouths[1].'222222'.'<br>';?>
<? echo $im_mouths[2].'333333'.'<br>';?>
I am not sure I'm doing correctly or not ,help me out this problem.
Thanks :)
It's only showing one image because you're re-writing $im_mouths each time you loop. You should change your loop to do the following:
$im_mouths = array();
if($objResult['Image_Type'] == '01') {
$img11 = array($objResult['Image_Name']);
for ($i=0; $i < count($img11[$i]); $i++) {
$im_mouths[] = array($img11[$i]);
}
}
We initialize $im_mouths as an array, then add each element to the array as an element: $im_mouths[] = ....
You need to simplify your code a bit.
Assuming you have a outer loop for retrieving data from database:
$im_mouths = array();
while ($objResult = $res->fetch()) {
if($objResult['Image_Type'] == '01') {
$im_mouths[] = $objResult['Image_Name'];
}
}
Now you have $im_mouths array of elements of image names, as many as you have in database. So as you see you don't need unnecessary inner for loop
Finally to see what you have in your $im_mouths array, you can print_r it:
print_r($im_mouths);
In your example, the variable $im_mouths should contain only the last image ( that is, 20140923jaobangsaen01.png ). Because you are using simple variable to store the image, so that the variable may contain last image while the program flow comes out from the for loop. So that the output of your example is correct. If you want to show each images means, you should use array variable to store all the images and display back to the required place. Rearrange the code like following,
$im_mouths = array();
if($objResult['Image_Type'] == '01') {
$img11 = array($objResult['Image_Name']);
for ($i=0; $i < count($img11[$i]); $i++) {
$im_mouths[] = array($img11[$i]);
}
}
Hope it will work fine for you.
Use can use foreach to display the images instead of using echo for each image.
$num = 1111; //if required
foreach ( $im_mouths as $value ) {
echo $value.$num;
$num += 1111;
}

How to check if JSON index (key) exists?

I have this API that returns this:
{"response":
[{"cid":5122405,"title":"Austin","area":"Estrie","region":"Quebec"},{"cid":5467453,"title":"Austin","region":"Manitoba"}]}
I want to print all areas, but as an example above, Austin in Quebec has area value (Estrie), but Austin in Manitoba doesn't.
My code is:
for($i = 0; $i < count($json_array['response']); ++$i){
echo $json_array['response'][$i]['area'];
but the problem is I get this error Notice: Undefined index: area in... where area value is not present (like Austin in Manitoba).
How can I check is area is present or not?
There's two basic ways to can deal with this problem.
The simplest is to check the existence of the variable
echo array_key_exists('area', $json_array['response'][$i]) ? $json_array['response'][$i]['area'] : null;
The other way is to standardise the response from the API so that the area key always exists
function standardizeApi($values)
{
foreach ($values['response'] as $i => $details) {
if (!array_key_exists('area', $details)) {
$values['response'][$i]['area'] = null; // default value
}
}
return $values;
}
$json_array = standardizeApi($json_array);
// loop though as normal
The second way is better if you have more than one key to check. You can ensure the array contains values, even if the api is missing them.
Edit: Spelling
quick if
for($i = 0; $i < count($json_array['response']); ++$i){
if($json_array['response'][$i]['area']){
echo $json_array['response'][$i]['area'];
};
You can use the json decode as an object and get the item list:
$stringJson = '{"response":[{"cid":5122405,"title":"Austin","area":"Estrie","region":"Quebec"},{"cid":5467453,"title":"Austin","region":"Manitoba"}]}';
$jsonObj = json_decode($stringJson);
foreach ($jsonObj->response as $item) {
echo $item->cid; // 5122405 5467453
}

Delete the whole row from an array in php

How do I delete the whole line from an array? When the delete-button is pressed it should delete the whole line.
my array looks like that:
$liste[0][0] = email-user1
$liste[0][1]= password-user1
$liste[1][0] = email-user2
$liste[1][1]= password-user2
So if I delete the user one, the user2 should just take the place from user1(which should just disappear).
if (isset($_GET['delete'])){
$id=key($_GET['delete']);
for ($i = 0; $i < count($liste); $i++){
if ("$i"=="$id"){
unset($liste[$id][0]);
unset($liste[$id][1]);
unset($liste[$id][2]);
}
else{
}
}
update
I'm using array_splice($liste, $id, 1); now but everytime I try to save it to the file I get an error: implode(): Invalid arguments passed. For saving it to the file, I use the following function:
function saveDataToFile($fileName, $liste){
$file=fopen($fileName,"w");
for ($i = 0; $i < count($liste); $i++) {
$zArray=$liste[$i];
$zeile=implode("|", $zArray);
if(strlen($zeile) > 0){
$zeile=$zeile."\r\n";
fwrite($file, $zeile);
}
}
fclose($datei);
}
Try the below code:
$liste[0][0] = "email-user1";
$liste[0][1]= "password-user1";
$liste[1][0] = "email-user2";
$liste[1][1]= "password-user2";
$liste[2][0] = "email-user3";
$liste[2][1]= "password-user3";
unset($liste[1]); // say you want to delete this row
$new_arr = $liste;
unset($liste);
$i=0;
foreach($new_arr as $value){
$liste[$i] = $value;
$i++;
}
You can use array_splice() method:
array_splice($liste, $id, 1);
$liste[0][0], $liste[0][1] and $liste[0][2] are in real nothing else than a value array(value, value, value) (the inner array) which is assigned to $liste[0] (the outer array)
unsetting this (outer) array value $liste[0] is enough:
unset($liste[$id]);
If you care about the keys of this array (I see you loop from 0..n), you need to reindex your array using:
$liste = array_values($liste);
This will make your array behaving more like arrays normally do in other programming languages
Good practice is to use foreach instead of for. In this case you don't need to reindex:
for ($liste as $key=>$value){
if ("$key"=="$id"){
unset($liste[$key]);
}
But anyway you don't have to loop through an array just for finding a key. It's enough doing this:
if (isset($liste[$id])) { /* optional: check if the key exists */ }
unset($liste[$id]);

Get the ids and loop through post data

I post a form with the same input names+id at the end like that:
<input type="text" name="machine_1">
<input type="text" name="machine_11">
<input type="text" name="machine_23">
How loop through on each of them and get the id's in the loop?
I tried this way, but it will loop a lot without any data and what happens if there is more thank 100 id?
for($i=0; $i<100; $i++){
$_POST["machine"]=$_POST["machine_".$i];
$id=$i;
}
POST is an associate array, so you can loop through everything that's been posted like this:
//$k contains the id
//$v contains the submitted value
foreach($_POST as $k => $v) {
//test if id contains 'machine'
if(stristr($k, 'machine')) {
echo $v;
}
}
You can do this using a foreach loop, like so:
foreach($_POST as $key => $value) {
echo "POST parameter '$key' has '$value';
}
$_POST["machine"]=$_POST["machine_".$i];
here $_POST['machine'] represents noting..how can you assign a value to $_POST['machine']..you havent passed any element having name machine while submitting the form..so first of all you need to check it bro
In your code, you have:
$_POST["machine"]=$_POST["machine_".$i];
That's not the correct way. You want to store the value of $_POST["machine_".$i] to $id and then use it below.
This is probably what you need:
for($i=1; $i<100; $i++){
$id = $_POST["machine_".$i];
echo $id;
}
And if there are more than 100 elements, and you don't know the number of inputs, then you can use a foreach loop, as below:
$i = 1; // counter variable
foreach ($_POST as $key => $input) {
if($key == "machine_".$i) {
$id = $input; // or simply 'echo $input'
echo $id;
}
$i++; // increment counter
}

Retrieve POST items with different names

I'm passing some values with POST to another file.
One (or more) of those values are:
Equip1, Equip2, Equip3, ..., EquipN
I'm able to know how many EquipN I have, but not know how to get their values.
I thought this works, but it's not:
for ($Equip_aux=1; $Equip_aux<=$Number_of_Equip; $Equip_aux++) {
$aux = "'Equipamento".$Equip."'";
$VALUE = $_POST[$aux];
}
Any help, please?
I'm able to know how many EquipN I have, but not know how to get their values.
Here's the corrected version of your for loop:
for ($i = 1; $i <= $Number_of_Equip; $i++) {
$aux = "Equip$i";
$VALUE = $_POST[$aux];
}
Notice that you can also loop trough the post values with foreach:
foreach ($_POST as $p) {
...
}

Categories