php passing several keys to a function - php

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';

Related

PHP - How to dynamically input multi-dimensional arrays only knowing the keys?

I have a multi-dimensional array with key value pairs. Some of the values of the keys are arrays, and some of the values in that array are arrays as well. It is only 3 branches deep (for now), but I am trying to recursively loop through the array, save the key for each level of the branch, and create a new array when it reaches a string that also mimics the structure of the original array. When it reaches a string, there should be a new object instantiation for each value.
The code below sort of does this, but only creates a flat array.
foreach ($data as $key => $value) {
if (!is_array($value)) {
$a_objects[$key] = new Component([$key], $value);
} else {
foreach ($value as $valueKey => $valueValue) {
if (!is_array($valueValue)) {
$a_objects[$key . "_" . $valueKey] = new Component([$key, $valueKey], $valueValue);
} else {
foreach ($valueValue as $k => $v) {
$a_objects[$key . "_" . $valueKey . "_" . $k] = new Component([$key, $valueKey, $k], $v);
}
}
}
}
Here is my own best attempt at this but it does not seem to save into the b_objects after some testing it does not seem to be saving the object instances.
$b_objects = [];
function create_r($data, $id)
{
foreach ($data as $key => $value) {
if (is_array($value) == true) {
array_push($id, $key);
create_r($value, $id);
} else {
array_push($id, $key);
$b_objects[$key] = new Component($id, $value);
$id = [];
}
}
}
$id = [];
create_r($data, $id);
echo "this is b_objects";
echo "<pre>";
print_r($b_objects);
echo "</pre>";
I verified that $id array contains the right "keys". I feel like this solution is pretty close but I have no idea how to use my $id array to mimic the structure of the $data.
I want to be able to say $b_objects[$level1key][$level2key][$level3key]...[$leveln-1key] = new Component...
Thanks!
I suggest you pass $b_objects by reference to your create_r() function. Otherwise each function call will instantiate a new $b_objects variable which is not used anywhere in the code afterwards.
Passing by reference allows the function to actually change the input array. Notice the & sign in the function declaration.
function create_r($data, $id, &$res)
{
foreach ($data as $key => $value) {
if (is_array($value) == true) {
array_push($id, $key);
create_r($value, $id, $res);
} else {
array_push($id, $key);
$res[$key] = new Component($id, $value);
$id = [];
}
}
}
$id = [];
$b_objects = [];
create_r($data, $id, $b_objects);

Own Framework won't pass variables

I'm doing a small PHP framework, I'm having issues passing the variables to the view...Here is what I do:
// $vars is : array("foo1" => "bar1", "foo2" => "bar2")
if(is_array($vars))
{
foreach ($vars as $key => $value)
{
$key = $value;
}
}
//add the view.
include($path);
}
So I'll like in my view access to $foo1 and $foo2, but they are NULL. How is the way to do it?
All you're doing is setting the value of the var $key to what it already is...
What I assume is your goal is getting the variables from the array into their own variable.
If that's the case then change
$key = $value;
Into
$$key = $value;
By using $$ your setting new variables with the name of the $key
// $vars is : array("foo1" => "bar1", "foo2" => "bar2")
foreach ($vars as $key => $value){
$$key = $value;
}
// results in:
// $foo1 = "bar1"
// $foo2 = "bar2"

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);

if empty $_POST assign value in foreach loop

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
}
}
}

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