Add values to $_SESSION['name'] then Loop thru values - php

I'm using a $_SESSION variable to store error codes in an app I'm creating.
On my form processing page, i'm using the following code (as an example):
session_start();
$_SESSION['site_msg'] = array();
if(1 == 1) {
$_SESSION['site_msg'] = 18;
}
if(2 == 2) {
$_SESSION['site_msg'] = 21;
}
if(3 == 3) {
$_SESSION['site_msg'] = 20;
}
I'm hoping to use a function to get the values from the array to use elsewhere in my code.
function error_code() {
foreach($_SESSION['site_msg'] as $value) {
echo "Value: $value <br />";
}
}
The above gives an error; Warning: Invalid argument supplied for foreach() ...
If I write the function like this:
$array[] = $_SESSION['site_msg'];
foreach($array as $value) {
echo "VAL: " . $value;
}
It only gives me the last value, 20.
Anyone have an idea where I went wrong?
Thanks!

<?php
session_start();
$_SESSION['site_msg'] = array();
if(1 == 1) {
array_push($_SESSION['site_msg'],18); // '=' overwrites the data, so push data in session array not to assign
}
if(2 == 2) {
array_push($_SESSION['site_msg'],21);
}
if(3 == 3) {
array_push($_SESSION['site_msg'],20);
}
$array = $_SESSION['site_msg']; //remove [] from variable, its not needed
foreach($array as $value) {
echo "VAL: " . $value;
}
?>

You declare your variable $_SESSION['site_msg'] as an array, but you pass integer values to this variable! You need to add your values as new array elements.
This should work:
session_start();
$_SESSION['site_msg'] = array();
if(1 == 1) {
$_SESSION['site_msg'][] = 18;
}
if(2 == 2) {
$_SESSION['site_msg'][] = 21;
}
if(3 == 3) {
$_SESSION['site_msg'][] = 20;
}
As an alternative you can use the function array_push() to add your values to the array:
session_start();
$_SESSION['site_msg'] = array();
if(1 == 1) {
array_push($_SESSION['site_msg'], 18);
}
if(2 == 2) {
array_push($_SESSION['site_msg'], 21);
}
if(3 == 3) {
array_push($_SESSION['site_msg'], 20);
}

Related

How to repeat the same action for diffrent variables

<!-- language: php -->
<?php
// test variables
$l1 = "http://youtube.com/channel/";
$l2 = "http://youtube.com/channel/";
$l3 = "http://youtube.com/channel/";
$l4 = "http://youtube.com/channel/";
$fl = "http://youtube.com/channel/";
//set error false as default
$error = "false";
//check if variables are ready for use, if they are, add them to `$l` array
//I do each check as a seperate line, as it looks cleaner than 1 long if statement.
$l = [];
if(!empty($l1)) $l[] = $l1;
if(!empty($l2)) $l[] = $l2;
if(!empty($l3)) $l[] = $l3;
if(!empty($l4)) $l[] = $l4;
if(!empty($fl)) $l[] = $fl;
foreach($l as $key => $value) {
//1 line ternary is cleaner than if/else statetmnt
$errorKey = $key < 9? "0{$key}" : $key;
//each row by default has no error
$hasError = 0;
//check if this a valid url
if(!preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $value)) {
$error = "true";
$hasError = 1;
}
if($hasError) {
//store error in array, to loop through later
$errors[] = $errorKey;
}
}
$search = '?sub_confirmation=1';
$searchUrl = "youtube.com/channel";
if (strpos($l, $searchUrl) !== false && strpos($l, $search) === false) {
$l = $value."".$search;
}
if($error == "false") {
echo $l1;
echo $l2;
echo $l3;
echo $l4;
echo $fl;
}
// deliver the error message
//Check if $error has been set to true at any point
if($error == "true") {
//loop through error array, echo error message if $errorNumber matches.
//at this point we KNOW there was an error at some point, no need to use a switch really
foreach($errors as $errorNumber) {
echo "Something went wrong here $errorNumber :o";
}
}
?>
Hello, my problem is at the end of the code where the strpos function is, so basically I want to check every url, once if it contains a certain url, and then add something to the end if it is so. But I don't want to repeat an if statement 4 times($fl variable doesn't has to be checked), I am quite new in all that so I hope somebody can help me, I tought about a switch statement but I guess there is a better way. And if I put it in the foreach aboth, it doesn't applies on the certain variables, only on the value variable.
You can assign $value by reference using this foreach header (notice the & in front of $value):
foreach($l as $key => &$value) {
By doing this every change you do to $value will also be done to the corresponding value in the $l array.
Then at the end of the foreach loop you put this code:
if (strpos($value, $searchUrl) !== false && strpos($value, $search) === false) {
$value .= $search;
}
So your final foreach loop should look like this:
foreach($l as $key => &$value) {
//1 line ternary is cleaner than if/else statetmnt
$errorKey = $key < 9? "0{$key}" : $key;
//each row by default has no error
$hasError = 0;
//check if this a valid url
if(!preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $value)) {
$error = "true";
$hasError = 1;
}
if($hasError) {
//store error in array, to loop through later
$errors[] = $errorKey;
}
$search = '?sub_confirmation=1';
$searchUrl = "youtube.com/channel";
if (strpos($value, $searchUrl) !== false && strpos($value, $search) === false) {
$value .= $search;
}
}
You can read more about using references in foreach loops here: PHP: foreach
Edit:
To apply the changes not only to the elements of the $l array, but also to the original variables $l1, $l2 and so on, you should assign the elements to your array as references too:
$l = [];
if(!empty($l1)) $l[] = &$l1;
if(!empty($l2)) $l[] = &$l2;
if(!empty($l3)) $l[] = &$l3;
if(!empty($l4)) $l[] = &$l4;
if(!empty($fl)) $l[] = &$fl;
Personally, I think this is a good candidate for moving to a class. To be honest I'm not 100% sure what you are doing but will try to convert your code to a class.
class L {
public $raw = null;
public $modified = null;
public $error = false;
// create the class
public function __construct($data=null) {
$this->raw = $data;
// Check the raw passed in data
if ($data) {
$this->isUrl();
}
// If there was no error, check the data
if (! $this->error) {
$this->search();
}
}
// Do something ?
public function debug() {
echo '<pre>';
var_dump($this);
echo '</pre>';
}
public function getData() {
return ($this->modified) ? : $this->raw;
}
private function isUrl() {
$this->error = (! preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $this->raw));
}
// Should a failed search also be an error?
private function search() {
if ($this->raw) {
if ( (strpos($this->raw, "youtube.com/channel") !== false) &&
(strpos($this->raw, "?sub_confirmation=1") === false) ) {
$this->modified = $this->raw ."?sub_confirmation=1";
}
}
}
}
// Test data
$testList[] = "test fail";
$testList[] = "https://youtube.com/searchFail";
$testList[] = "https://youtube.com/channel/success";
$testList[] = "https://youtube.com/channel/confirmed?sub_confirmation=1";
// Testing code
foreach($testList as $key=>$val) {
$l[] = new L($val);
}
foreach($l as $key=>$val) {
// Check for an error
if ($val->error) {
$val->debug();
} else {
echo '<pre>'.$val->getData().'</pre>';
}
}
And the output would be:
object(L)#1 (3) {
["raw"]=>
string(9) "test fail"
["modified"]=>
NULL
["error"]=>
bool(true)
}
https://youtube.com/searchFail
https://youtube.com/channel/success?sub_confirmation=1
https://youtube.com/channel/confirmed?sub_confirmation=1

PHP output only one value in for each

I'm having trouble with output in for each function in PHP (actually don't know how to set the code to do what I need). I'd like to output some text if every item in foreach is equal to some value. If I put
foreach($items as $item) {
if($item == 0){ echo "true"; }
}
I will get true for every item and I need to output true only if all items are equal to some value.
Thanks!
This is most likely due to PHP type juggling your values. Your values are probably not numeric so when you do a loose comparison (==) PHP converts them to integers. Strings that do not start with digits will become zero and your statement will be true.
To fix this use the === comparison operator. This will compare value and type. So unless a value is the integer zero it will be false.
if($item === 0){ echo "true"; }
If you are trying to see if all items are equal to some value this code will do this for you:
$equals = 0;
$filtered = array_filter($items, function ($var) use ($equals) {
return $var === $equals;
});
if (count(count($items) === count($filtered)) {
echo "true";
}
This peice of code work for most type of variables. See how it works in inline comment.
$count=0; // variable to count the matched words
foreach ($items as $item)
{
if($item == $somevalue)
{
$count++; // if any item match, count is plus by 1
}
}
if($count == count($items))
{
echo "true"; // if numbers of matched words are equal to the number of items
}
else
{
echo "false";
}
Hope it works , And sorry for any mistake
$ok = true;
foreach ($items as $item)
{
if ($item != 0)
{
$ok = false;
}
}
if ( $ok == true)
{
echo 'true';
}
$bool = 0;
foreach($items as $item) {
if($item == $unwantedValue)
{ $bool=1; break; }
}
if($bool==0)
echo 'true';
$equals=true;
foreach($items as $item) {
if($item!=0)
{
$equals=false;
break;
}
}
if($equals) {
echo 'true';
}
if you want to check the values is same with some value in variabel and print it use this
<?php
$target_check = 7;
$items = array(1, 4, 7, 10, 11);
foreach ($items as $key => $value) {
if ($value == 7) echo "the value you want is exist in index array of " . $key . '. <br> you can print this value use <br><br> echo $items[' . $key . '];';
}
?>
but if you just want to check the value is exist in array you can use in_array function.
<?php
$target_check = 2;
if (in_array($target_check, $items)) echo "value " . $target_check . 'found in $items';
else echo 'sorry... ' . $target_check . ' is not a part of of $items.';
?>
<?
$items=array(0,1,2,0,3,4);
foreach($items as $item) {
if($item == 0){ echo "true"; }
}
?>
your code work!
check the source of the $items array

Getting a particular array and echo its value

I have this script from a free website file. Here is the subject script:
foreach ($auth as $a => $a1) {
//$a = strtoupper($a);
if (in_array($a, array('CASH','VOTE','ID','IP','PLAYTIME','PCOIN','CREATEDATE','LAST','SPENT','CONNECTSTAT','VIP','VIP_FREE','EXPIRED','CTL1_CODE'))) {
if ($a == 'CTL1_CODE') {
$a = 'STATUS';
$a1 = user_status($a1,'ctl');
}
$results[] = array('name'=>preg_replace('/_/i',' ',$a),'data'=>$a1);
}
}
How to get the value of ID and echo it?
When you clean up the code, it’s easy to see how to access the ID value:
foreach ($auth as $a => $a1) {
//$a = strtoupper($a);
if (in_array($a, array('CASH','VOTE','ID','IP','PLAYTIME','PCOIN','CREATEDATE','LAST','SPENT','CONNECTSTAT','VIP','VIP_FREE','EXPIRED','CTL1_CODE'))) {
if ($a == 'CTL1_CODE') {
$a = 'STATUS';
$a1 = user_status($a1,'ctl');
}
if ($a == 'ID') {
echo $a1;
}
$results[] = array('name'=>preg_replace('/_/i',' ',$a),'data'=>$a1);
}
}
Just adding the check for ID will work:
if ($a == 'ID') {
echo $a1;
}
EDIT And if you want to access it outside of the foreach loop, just do this. I have an if conditional to just check if the value exists.
if (array_key_exists('ID', $auth) && !empty(trim($auth['ID'])) {
echo $auth['ID'];
}
Or, since your foreach loop is creating $results you can access that value this way instead:
if (array_key_exists('ID', $results) && !empty(trim($results['ID'])) {
echo $results['ID'];
}

Storing array in a variable

I'm trying to replace the code below
$Palette = array(
"0"=>array("R"=>188,"G"=>224,"B"=>46,"Alpha"=>100),
"1"=>array("R"=>188,"G"=>224,"B"=>46,"Alpha"=>100),
"2"=>array("R"=>188,"G"=>224,"B"=>46,"Alpha"=>100),
"3"=>array("R"=>188,"G"=>224,"B"=>46,"Alpha"=>100),
"4"=>array("R"=>176,"G"=>46,"B"=>224,"Alpha"=>100),
);
with something similar but different values for the R, G and B. I have written the code below so far as a replacement:
$x = '0';
$incrementarray = array("0"=>"A","1"=>"B","2"=>"C","3"=>"D","4"=>"E");
do
{
if ($correct == $incrementarray[$x])
{
$colour[$x] = '"'.$x.'"=>array("R"=>188,"G"=>224,"B"=>46,"Alpha"=>100),';
}
else
{
$colour[$x] = '"'.$x.'"=>array("R"=>255,"G"=>51,"B"=>51,"Alpha"=>100),';
}
$x++;
}
while ($x <= '4');
$allcolours = $colour[0].$colour[1].$colour[2].$colour[3].$colour[4];
however, when I implement it into my script using the line below , it doesn't work.
$Palette = array($allcolours);
$x = '0';
$incrementarray = array("0"=>"A","1"=>"B","2"=>"C","3"=>"D","4"=>"E");
do
{
if ($correct == $incrementarray[$x])
{
$Pallete[$x] = array("R"=>188,"G"=>224,"B"=>46,"Alpha"=>100);
}
else
{
$Pallete[$x] = array("R"=>255,"G"=>51,"B"=>51,"Alpha"=>100);
}
$x++;
}
while ($x <= '4');
there is a little excessive usage of $x.
as a matter of fact, you don't need that variable at all
$Palette = array();
$incrementarray = array("0"=>"A","1"=>"B","2"=>"C","3"=>"D","4"=>"E");
foreach ($incrementarray as $value)
{
if ($correct == $value)
{
$Palette[] = array("R"=>188,"G"=>224,"B"=>46,"Alpha"=>100);
}
else
{
$Palette[] = array("R"=>255,"G"=>51,"B"=>51,"Alpha"=>100);
}
}
you need to create array, not the PHP code to create array.

for loop and if loop is refusing to print a varriable outside the loop?

i am facing a problem that after i created the jQuery post, i was able to receive all the data but as a one peace, so when i began rephrasing them i succeed until the final part which was the inserting into the database, where inside the for loop and if loop i am getting the value but when i wanted to start inserting them into the database i am getting null values, below is the for loop and if loop
if ($action == "insert")
{
$fields = explode("&",$data);
foreach($fields as $field)
{
$field_key_value = explode("=",$field);
$key = urldecode($field_key_value[0]);
$value = urldecode($field_key_value[1]);
$id = $row['id'];
$date1 = date("d/n/Y");
foreach ($cart->get_contents() as $item)
{
$item_id = $item['id'];
$item_name = $item['name'];
$item_price = $item['price'];
$item_qty = $item['qty'];
$item_ids = explode("-",$item_id);
for($i = 0; $i < count($item_ids); $i++)
{
$item_idn = join("",$item_ids);
}
if($key == $item_id."id")
{
$ids = $value;
echo $ids."\r\n";
}
elseif($key == "Small".$item_idn)
{
$small= $value;
echo $small."\r\n";
}
elseif($key == "large".$item_idn)
{
$large= $value;
echo $large."\r\n";
}
elseif($key == "medium".$item_idn)
{
$medium= $value;
echo $medium."\r\n";
}
elseif($key == "xlarge".$item_idn)
{
$xlarge= $value;
echo $xlarge."\r\n";
}
elseif($key == "qty".$item_idn)
{
$qty = $value;
echo $qty."\r\n";
}
elseif($key == "Total".$item_idn)
{
$subtotal = $value;
echo $subtotal."\r\n";
}
elseif($key == "finaltotal")
{
$finaltotal = $value.",";
$final = explode(",",$finaltotal);
for($i = 0; $i < count($final); $i++)
{
$totalf = $final[$i];
break 3;
}
}
}
}
}
From jQuery docs:
The .serialize() method creates a text string in standard URL-encoded notation
So on the PHP side you'll get a similar string like this:
a=1&b=2&c=3&d=4&e=5
There's no need to explode &'s (or any other hocus-pocus) you can easily access your submitted variables like:
$a = $_POST['a']; //1
Of course when you submit your data via $_GET, you need to use $_GET.
It appears as if you have a number of issues. If your jQuery is posting to your PHP script you can get all your keys/values through the $_POST array. You could get $finaltotal like this $finaltotal = $_POST['finaltotal']. If your jQuery is not POSTing, but sending them as a GET request, you can get the same value like so $finaltotal = $_GET['finaltotal'].
Also, regarding your big if/elseif block of code, I would recommend using a switch statement instead if you are going to keep your code as is.
switch($key)
{
case 'finaltotal':
//do stuff
break;
default:
//do default
break;
}
First of all, you either can use $_GET/$_POST for the submited data, as fabrik pointed out, or (if for some reason you really only have your data in $data) can use the built in function parse_str.
parse_str($data, $fields);
foreach($fields as $key => $field) {
foreach ($cart->get_contents() as $item) {
if($key == ...) {
...
}
}
}
And if I correctly understand what you are doing here, you need to move the break 3; out of your for loop:
elseif($key == "finaltotal") {
$finaltotal = $value.",";
$final = explode(",",$finaltotal);
for($i = 0; $i < count($final); $i++){
$totalf = $final[$i];
}
break 3;
}

Categories