if empty $_POST assign value in foreach loop - php

Hi want to build a program which creates surveys. I couldn' t figure out how can i assign value for a question which is unanswered. Thank you for your helps.
$dizi = array();
foreach ( $_POST as $key => $value){
if(empty($_POST)){
$_POST="bos";
}
$dizi[$key] = "'".$value."'";
}

Your code doesn't make sense, try this:
$dizi = array();
foreach($_POST as $key => $value) {
if (empty($value)) {
$value = 'your value';
}
$dizi[$key] = $value;
}

$_POST is an associative array
So you can access it with:
$bla = $_POST['bla'];
What you are trying to do is setting the whole array to a string which doesn't work.
You should set the new value when saving it to the $dizi array.
$dizi = array();
foreach($_POST as $key => $value) {
$newValue = $value;
if (empty($value)) {
$newValue = 'bos';
}
$dizi[$key] = $newValue;
unset($newValue);
}
But this only checks if answer string is empty. So this only works if all questions are mandatory.

If I understood you correctly, what you are trying to do is this:
foreach ( $_POST as $key => $value ) {
if(empty($value))
$_POST[$key] = 'This is an unanswered question!';
}
But this cannot work due to the fact that empty values aren't posted from the form.

How do you know that there is 'unanswered' question if it was not posted from the form?
You have to start from the list of the questions (which can not be forged by the user and is defined on the server-side) and check that answer for each of them exists in $_POST. If not - assign whatever you want to the skipped answers.

Try this:
if(isset($_POST) && (!empty($_POST))){
foreach ( $_POST as $key => $value ) {
if(empty($value)){
$_POST="bos";
} else{
//put your code
}
}
}

Related

php passing several keys to a function

Im using a function to update $_SESSION data
function session_values($key, $value)
{
if(empty($_SESSION[$key])
{
$_SESSION[$key] = $value;
}else if($_SESSION[$key] != $value)
{
$_SESSION[$key] = $value;
};
};
session_values($key, $value);
question is, how to use this function, add a $_SESSION value equal to
$_SESSION['thispage']['signup']['name'] = 'Bob';
for example.
Like this:
$key = 'thispage';
$value = ['signup' => ['name' => 'Bob']];
session_values($key, $value);
This should have the same effect as
$_SESSION['thispage']['signup']['name'] = 'Bob';

Dynamically check for strings in a PHP array

EDIT: ten months later, I'm still back to this.. still can't figure it out :(
I can search for a string in an array no problem; this works:
if (in_array('animals', $value[tags])){
echo "yes";
}
But how can I check for a variable in the array? This doesn't seem to work:
$page_tag = 'animals';
if (in_array($page_tag, $value[tags])){
echo "yes";
}
I'm guessing I'm missing some simple syntax doodad?
The array is massive, so I'll try and show a sample of it. It is stored on a separate php file and "included" in other places.
global $GAMES_REPOSITORY;
$GAMES_REPOSITORY = array (
"Kitten Maker" => array (
"num" => "161",
"alt" => "Kitten Maker animal game",
"title" => "Create the kitten or cub of your dreams!",
"tags" => array ("animals", "feline", "cats", "mega hits"),
),
}
Here's a larger part of the code, to put into context. It pulls from the array of ~400 games, and pulls the ones with a specific tag:
function array_subset($arr) {
$newArray = array();
foreach($arr as $key => $value) {
if (in_array($page_tag, $value["tags"])){
if(is_array($value)) $newArray[$key] = array_copy($value);
else if(is_object($value)) $newArray[$key] = clone $value;
else $newArray[$key] = $value;
}
}
return $newArray;
}
function array_copy($arr) {
$newArray = array();
foreach($arr as $key => $value) {
if(is_array($value)) $newArray[$key] = array_copy($value);
else if(is_object($value)) $newArray[$key] = clone $value;
else $newArray[$key] = $value;
}
return $newArray;
}
$games_list = array();
$games_list = array_subset($GAMES_REPOSITORY);
$games_list = array_reverse($games_list);
Oh, an interesting hint. Elsewhere it DOES work using $_GET:
if (in_array($_GET[tagged], $value[tags])){
The in_array() function can check variables, so it is likely that your problem comes from somewhere else. Verify that you've defined your constant tags correctly. If it's not defined, it might not work depending on your PHP version. Some versions just assume that you wanted to write the string tags instead of a constant named tags.
Your code works. Here's a full example that I've tested that works well:
<?php
const tags = "tags";
$page_tag = 'animals';
$value = array('tags' => array("fruits", "animals"));
if (in_array($page_tag, $value[tags])){
echo "yes";
}
You have an array of arrays, so in_array() wont work as you have written it as that test for existence in an array, not a subarray. You may as well just loop through your arrays like this:
foreach($GAMES_REPOSITORY as $name =>$info) {
if(in_array($page_tag, $info['tags']))
{ whatever }
}
If that is not fast enough you will have to cache your tags by looping ahead of time and creating an index of tags.
I finally got it to work! I don't entirely understand why, but I had to feed the variable into the function directly. For some reason it wouldn't pull the variable from the parent function. But now it works and it even takes two dynamic variables:
function array_subset2($arr, $tag1, $tag2) {
$newArray = array();
foreach($arr as $key => $value) {
if (in_array($tag1, $value['tags'])){
if (in_array($tag2, $value['tags'])){
if(is_array($value)) $newArray[$key] = array_copy2($value);
else if(is_object($value)) $newArray[$key] = clone $value;
else $newArray[$key] = $value;
}
}
}
return $newArray;
}
function array_copy2($arr) {
$newArray = array();
foreach($arr as $key => $value) {
if(is_array($value)) $newArray[$key] = array_copy2($value);
else if(is_object($value)) $newArray[$key] = clone $value;
else $newArray[$key] = $value;
}
return $newArray;
}
$games_list = array();
$games_list = array_subset2($GAMES_REPOSITORY, $page_tag, $featured_secondary_tag);

how to split stored variables name inside foreach

How can i know the variables ?
foreach($tree as $key => $value){
if (in_array($value['name'], $arr_folders)) {
${'id_'.$value['name']} = $value['id'];
}
//how to know variables?
$id_???
Currently I know the $value['name'] ie. it may be one,two, three, etc. but how to use them
echo $id_one;
I wanted to know here to split them in an array. So i can use
print_r($vars); which would result $id_one, $id_two, etc..
Something like this?
<?php
$array = [];
foreach($tree as $key => $value){
if (in_array($value['name'], $arr_folders)) {
$array[] = $value['id'];
}
}
print_r($array);
You can find variables by code:
foreach (get_defined_vars() as $var_name => $var_value) {
if(strpos($var_name, 'id_') ===0 ){
//it's your variable
}
}
But store variable in local scope look wrong.
May be better store to an other array:
$arIds = array();
foreach($tree as $key => $value){
if (in_array($value['name'], $arr_folders)) {
$arIds['id_'.$value['name']] = $value['id'];
}
}

How to get index's value from $_POST using foreach

I want to know the correct code to detect only numerical $_POST fields coming from the form.
Please correct my code.
foreach ($_POST as $vals) {
if (is_numeric($vals)) {
if (is_numeric($vals[$i]) && ($vals[$i]!="0")) {
//do something
}
}
$_POST = array_filter($_POST, "is_numeric");
The above will remove all non-numeric array items.
foreach (array_filter($_POST, "is_numeric") as $key => $val)
{
// do something
echo "$key is equal to $val which is numeric.";
}
Update:
If you only want those like $_POST[1], $_POST[2], etc..
foreach ($_POST as $key => $vals){
if (is_numeric($key)){
//do something
}
}
try:
foreach ($_POST as $key => $vals){
//this is read: $_POST[$key]=$value
if (is_numeric($vals) && ($vals!="0")){
//do something
}
}
if(isset($_POST)){
foreach($_POST as $key => $value){
if(is_numeric($key)){
echo $value;
}
}
}
Compare the keys
Try this:
foreach ($_POST as $key => $val)
{
if (is_numeric($key))
{
// do something
}
}
The following code with isset() trying to work on an array is invalid.
if(isset($_POST)){ //isset() only works on variables and array elements.
foreach($_POST as $key => $value){
if(is_numeric($key)){
echo $value;
}
}
foreach ($_POST as $key => $val)
{
if (is_numeric($key))
{
// do something
}
}
Better, but now foreach will make a copy of $_POST and put in in memory for the duration of the loop (Programming PHP: Ch. 6, p. 128-129). I hope buffer overflows or out of memory errors don't jump up and bite you. :-)
Perhaps it would be wiser to determine some facts about $_POST with is_array(), empty(), count() and others before getting started, such as ...
if(is_array($_POST) && !empty($_POST))
{
if(count($_POST) === count($arrayOfExpectedControlNames))
{
//Where the the values for the $postKeys have already been validated some...
if(in_array($arrayOfExpectedControlNames, $postKeys))
{
foreach ($_POST as $key => $val) //If you insist on using foreach.
{
if (is_numeric($key))
{
// do something
}
else
{
//Alright, already. Enough!
}
}
}
else
{
//Someone is pulling your leg!
}
}
else
{
//Definitely a sham!
}
}
else
{
//It's a sham!
}
Still, the $val values need some validation, but I'm sure you are up on that.

Saving post values in a session array

I want to save values send via POST in a session array:
$reply = array('thread_id', 'reply_content');
$_POST['thread_id'] = 2; # test it
$_SESSION['reply'] = array();
foreach ($reply as $key)
{
if (in_array($key, $_POST))
{
$_SESSION['reply'][$key] = $_POST[$key];
}
}
var_dump($_SESSION['reply']);
For example I want to check if the keys 'thread_id' and 'thread_content' are send in post, if they are then I want to save them in a session array called reply, using the same keys.
So for example if 'thread_id' is send via POST:
$_POST['thread_id'] = 'blah';
Then this should get saved in a session called 'reply', using the same key:
$_SESSION['reply']['thread_id'] = 'blah';
How can this be done?
In general, your approach looks valid, but I'm going to guess that you may not be calling session_start(), which is necessary to persist session data.
session_start();
if(!$_SESSION['POST']) $_SESSION['POST'] = array();
foreach ($_POST as $key => $value) {
$_SESSION['POST'][$key] = $value;
}
var_dump($_SESSION['POST']);
in_array($needle, $haystack) checks whether $needle is a value in $haystack and not a key. Use array_key_exists or isset instead:
foreach ($reply as $key)
{
if (array_key_exists($key, $_POST))
{
$_SESSION['reply'][$key] = $_POST[$key];
}
}
Or:
$_SESSION['reply'] = array_merge($_SESSION['reply'], array_intersect_key($_POST, array_flip($reply)));
Use this
$reply = array('thread_id', 'reply_content');
$_POST['thread_id'] = 2; # test it
$_SESSION['reply'] = array();
foreach ($reply as $key)
{
if (isset($_POST[$key]))
{
$_SESSION['reply'][$key] = $_POST[$key];
}
}

Categories