Array will only echo last output when saving to a variable PHP - php

I have the following function in my php program.
$out = "";
printArray($_POST);
function printArray($array){
global $out;
foreach ($array as $key => $value){
$out = "$key: $value <br>";
}
}
echo $out;
Its supposed to get all my post values along with there variable names and save it all to a variable but it only echos out the last one in my list. Meanwhile if i dont save the output of the foreach to a variable...
printArray($_POST);
function printArray($array){
foreach ($array as $key => $value){
echo "$key: $value <br>";
}
}
it outputs just fine.
first_name: Test
last_name: Test
dob1:
dob2:
dob3:
current_grade:
shcool:
M_C:
type_of_session_text:
date_session_info:
(shortened for brevity)
whats going on here?

This is because every itteration you set $out again without keeping the previous values. You could do:
function printArray($array){
foreach ($array as $key => $value){
$out .= $key.": ".$value."<br>";
}
return $out;
}
With the .= you "add" more string to that variable. The technical term is 'concatenate'.
Also, global should be avoided as it is a mayor red flag of bad programming. A function should return a value, the logic that calls the function decides what to do with it. I recommend you do a little research into 'pure' functions (easy concept).

Related

save output of a foreach ($array as $key => $value) as a readable variable

I have the following function.
printArray($_POST);
function printArray($array){
foreach ($array as $key => $value){
echo "$key: $value <br>";
}
}
I modified it from here... Print $_POST variable name along with value
It gets all my html values along with there variable names and echos them. I need to save the output to variable. I've tried using ob..
printArray($_POST);
ob_start();
function printArray($array){
foreach ($array as $key => $value){
echo "$key: $value <br>";
}
}
$out = ob_get_contents();
ob_end_clean();
print $out;
and that just gives me nothing. Ive tried just saving my echo to a variable and that gets me closer...
&out = “”
function printArray($array){
foreach ($array as $key => $value){
$out = "$key: $value <br>";
}
}
but it only gives me the last value in my output. Help me out here what am i doing wrong.
NOTE: I screwed up and forgot to modify one of my functions to show what I was doing, whoops..
See screenshot:
<?php
printArray($_POST);
function printArray($array){
$result = [];
foreach ($array as $key => $value){
$result[] = (object)[
$key => $value
];
}
header('Content-Type: application/json; charset=utf-8');
echo json_encode($result);
}

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

Get JSON Array With PHP

I have the following JSON string, I'm wanting to cycle through the 'sub' items and print them out as HTML Select Options but for some reason I can't quite get hold of them.
Only used JSON a couple times before so it's probably a rookie mistake somewhere.
{
"1":{
"question":"How happy are you with your car?",
"sub":[
"Very Happy",
"Not So Happy",
"Unhappy",
"Very Unhappy"
]
}
}
I have the following which let's me echo out the Question Value but how would I loop through each of the 'sub' arrays? (There's only ever going to be 1 question which is why I'm storing it in a single variable)
$questionAnswer = json_decode($data->question,true);
foreach ($questionAnswer as $key => $value) {
$question = $value['question'];
}
Add another loop inside the existing one:
$questionAnswer = json_decode($data->question,true);
foreach ($questionAnswer as $key => $value) {
$question = $value['question'];
echo $question."<br>";
// value['sub'] contains the array of 'subs', so you can loop through that the same way
foreach ($value['sub'] as $sub) { // since the key will be 0,1,2 you might not need it here, so I omitted it.
echo $sub."<br>";
}
}
foreach ($questionAnswer as $key => $value) {
$question = $value['question'];
foreach ($value['sub'] as $answer) {
echo $answer;
}
}

modify key in a foreach loop php

I want to change the value of the $key because I have array_splice inside the loop which change the position of my values so - it mess up the value I need in a specific place.
I tried $key-- but it doesn't work.
for example when I print the $key after I do echo $key it's fine but when I echo $key just after the foreach loop I get the worng value.
Any ideas?
foreach ($cut as $key => $value) {
echo "foreach key:".$key."<br>";
if(in_array($value,$operators))
{
if($value == '||')
{
echo "found || in position:".$key."<br>";
if(($key+1<sizeof($cut)))
{
$multi = new multi;
echo "<br>"."key-1: ";
print_r($cut[$key-1]);
echo"<br>";
echo "<br>"."key+1: ";
print_r($cut[$key+1]);
echo"<br>";
$res = $multi->orex($cut[$key-1],$cut[$key+1],$numString);
$cut[$key-1]= $res;
array_splice($cut,$key,1);
array_splice($cut,$key,1);
$key--; //here trying to change the key
echo "new string:";
print_r($cut);
echo "<br>";
echo "key:".$key."<br>";
}
}
}
}
Updated
I don't think it is a good idea to change the array itself inside the foreach loop. So please crete another array and fill data into it, which will be your result array. This method works well when your array data is not big, in other words, most situations.
Origin
I don't know what do you mean. Let me give it a guess...
You want:
foreach($arr as $key=>$val){
$newkey = /* what new key do you want? */
$arr[$newkey] = $arr[$key];
unset($arr[$key]);
}

how can i get multidimensional array values using foreach?

I want to use a multidimensional array in different functions.so i am making it as a global variable(array).i created a multidimensional array and made it as global to access in different function.now how can i get the values from it using foreach loop?
here is my code
$test=array(
array(
"input1"=>"v1",
"input2"=>"v2"),
array(
"input3"=>"v3",
"input4"=>"v4")
);
class testing
{
function testp()
{
global $test;
foreach($test as $key => $value)
{
echo $value;
}
var_dump($test);
echo is_array($test);
}
}
$obj = new testing();
$obj->testp();
i used is_array and var_dump to confirm whether its an array.
all are fine
and its shwoing Error suppression ignored. now how can i get the values from it?
It is array of arrays, what works for top order array, works further as well:
foreach($test as $key => $value)
{
foreach($value as $k => $v){
echo $v;
}
}
This will echo your values v1, v2, v3, v4 one after another.
More general answer:
public function visitArray($test)
{
foreach($test as $key=>$value)
{
if(is_array($value))
{
visitArray($value);
}
else
{
echo $value;
}
}
}
Edit
Don't know why you're looping over keys and values, if key isn't took into account
More easy & simple way to access array values within a array.
foreach($test as $array_value){
if(is_array($array_value)) {
foreach ($array_value as $value) {
echo $value.'<br>';
}
}
}

Categories