PHP Session, why array is set to 1 - php

I am creating a notification class which uses the session to store messages. I need to create them as a multidimensional array, so I can take advantage of different 'namespaces', so as to keep messages from displaying on the wrong pages.
Here is an example:
print_r($_SESSION)
Array
(
[EVENT_CMS] => Array
(
[Notifier] => Array
(
[0] => 'Your settings have been saved.'
[1] => 'You must re-upload...'
)
)
)
Now on the settings page, these messages will print with a call to the proper method.
I am having trouble setting up the message container within the class. This is what my constructor looks like:
public function __construct($namespace = 'Notifier') {
$this->_session_start();
if(defined('SESSION_NAMESPACE')){
$this->notifications =& $_SESSION[SESSION_NAMESPACE][$namespace];
} else {
$this->notifications =& $_SESSION[$namespace];
}
}
(The SESSION_NAMESPACE constant is defined, so the true block is executed.)
$Notify = new Notifier();
$Notify->add($_GET['test']);
print_r($_SESSION);
The above code yields me this array:
$_SESSION
Array
(
[EVENT_CMS] => Array
(
[Notifier] => 1
)
)
The add message method should update the session, right? Since the notifications array is a reference? The call to update_session() has no effect on the output...
public function add($message, $class = NULL) {
$message_node = $message;
$this->notifications[] = $message_node;
$this->update_session();
}
public function update_session(){
$this->SESSION[$this->namespace] &= $this->notifications;
}

You are mixing up the bitwise operator with the reference operator. The wrong one is used in your update_session() method.

Related

Accumulate strings and array values into an array as a class property via method

I have a class with method add() that accepts strings and arrays. I need to have an array with all users, but I cannot seem to get it. All I get is multiple arrays with all users. How could I merge those arrays into one?
class Users {
function add($stringOrArray) {
$arr = array();
if(is_array($stringOrArray)) {
$arr = $stringOrArray;
} else if(is_string($stringOrArray)) {
$arr[] = $stringOrArray;
} else {
echo('errrrror');
}
print_r($arr);
}
When I use this test:
public function testOne() {
$users = new Users();
$users->add('Terrell Irving');
$users->add('Magdalen Sara Tanner');
$users->add('Chad Niles');
$users->add(['Mervin Spearing', 'Dean Willoughby', 'David Prescott']);
This is what I get, multiple arrays but I need one array.
Array
(
[0] => Terrell Irving
)
Array
(
[0] => Magdalen Sara Tanner
)
Array
(
[0] => Chad Niles
)
Array
(
[0] => Mervin Spearing
[1] => Dean Willoughby
[2] => David Prescott
)
You can cut a lot of unnecessary bloat from your method.
You can cast ALL incoming data to array type explicitly. This will convert a string into an array containing a single element. If the variable is already an array, nothing will change about the value.
Use the spread operator (...) to perform a variadic push into the class property.
Code: (Demo)
class Users
{
public $listOfUsers = [];
function add($stringOrArray): void
{
array_push($this->listOfUsers, ...(array)$stringOrArray);
}
}
$users = new Users;
$users->add('Terrell Irving');
$users->add(['Magdalen Sara Tanner', 'Chad Niles']);
$users->add(['Mervin Spearing']);
var_export($users->listOfUsers);
Output:
array (
0 => 'Terrell Irving',
1 => 'Magdalen Sara Tanner',
2 => 'Chad Niles',
3 => 'Mervin Spearing',
)
All you need is to store the added users in a class property, for example $listOfUsers.
If adding the array you use the array_merge() function otherwise just add new user at the end of indexed array.
<?php
class Users {
// here will be all the users stored
public $listOfUsers = array();
function add($stringOrArray) {
//$arr = array();
if(is_array($stringOrArray)) {
// merge two arrays - could create duplicate records
$this->listOfUsers = array_merge($this->listOfUsers, $stringOrArray);
} else if(is_string($stringOrArray)) {
// simply add new item into the array
$this->listOfUsers[] = $stringOrArray;
} else {
echo('errrrror');
}
print_r($this->listOfUsers);
}
}
In your example you are storing the data locally within the method add() and it is not kept for future usage. This behavior is corrected using the class property $listOfUsers that can be accesed using $this->listOfUsers within the class object and if needed outside of the class.

PHP class to find value in array from session

I am trying to make a simple class that I can use to check if a value exists within an array. There is a session that contains multiple tool values. I am trying to pass the toolID to this function as well as a key and see if that value exists.
Session Data:
Array
(
[keyring] => Array
(
[tool] => Array
(
[toolID] => 1859
[keys] => Array
(
[0] => 49
[1] => 96
)
)
)
)
class Keyring
{
public function checkKey($key, $toolID){
$keyring = $_SESSION['keyring'];
if(isset($keyring)){
foreach($keyring['tool'] as $k => $v) {
if($k == 'toolID' && $v == $toolID){
if (in_array($key, $k->keys)){
return true;
}
}
}
}
return false;
}
}
$keyring = new Keyring();
print_r($keyring->checkKey(49, 1859));
In this example, I am trying to see if key 49 exists in the session for tool 1859.
I am getting the following error : Warning: in_array() expects parameter 2 to be array, null given in.
Is there a better approach for this? All I am looking for is a true/false as to whether that key exists in the keys array for the specified tool.
For my code to work for you may need to change your array a bit or change the code a bit, but rather then looping through a bunch of keys trying to find the right one we are just looking for the keys in the array if they are not set, then return false, or if we find keyring - tools - $tool_id - key_{$key_id} we are just going to return that value, if key_49 = false the function returns false. This should be a tad bit quicker to run on the server for you.
function has_keyring($tool_id, $key_id)
{
//Just to keep the code tidy let's store the tools key in $tool variable
$tool = $_SESSION['keyring']['tools'];
if(isset($tool[$tool_id]) && isset($tool[$tool_id]["key_{$key_id}"]))
return $tool[$tool_id]["key_{$key_id}"];
return false;
}

PHP - adding an object with its properties to array

I have a problem with modifying an array.
foreach ($page->getResults() as $lineItem) {
print_r($lineItem->getTargeting()->getGeoTargeting()->getExcludedLocations());
}
This code gives a result:
Array
(
[0] => Google\AdsApi\Dfp\v201611\Location Object
(
[id:protected] => 2250
[type:protected] => COUNTRY
[canonicalParentId:protected] =>
[displayName:protected] => France
)
)
I'm trying to add another, [1] , same type of object to this array.
I made a class to create and add an object:
class Location{
public function createProperty($propertyName, $propertyValue){
$this->{$propertyName} = $propertyValue;
}
}
$location = new Location();
$location->createProperty('id', '2792');
$location->createProperty('type', 'COUNTRY');
$location->createProperty('canonicalParentId', '');
$location->createProperty('displayName', 'Turkey');
array_push($lineItem->getTargeting()->getGeoTargeting()->getExcludedLocations(), $location);
Then, if I pass this into print_r() function
print_r($lineItem->getTargeting()->getGeoTargeting()->getExcludedLocations());
It shows the same result.
In the end, I need to send this updated whole $lineItem to this function
$lineItems = $lineItemService->updateLineItems(array($lineItem));
But seems like before sending I can't properly add an object to the array.
Thanks in advance.
PHP returns arrays as a value instead of as a reference. This means you must set the modified value back somehow.
Looking at the library apparently in question, there seems to be setExcludedLocations method for that purpose.
So your code should be something like:
$geo_targeting = $lineItem->getTargeting()->getGeoTargeting();
$excluded_locations = $geo_targeting->getExcludedLocations();
array_push($excluded_locations, $location);
$geo_targeting->setExcludedLocations($excluded_locations);

How to create array of objects in php

I'm attempting to create an array of objects in php and was curious how I would go about that. Any help would be great, thanks!
Here is the class that will be contained in the array
<?php
class hoteldetails {
private $hotelinfo;
private $price;
public function sethotelinfo($hotelinfo){
$this->hotelinfo=$hotelinfo;
}
public function setprice($price){
$this->price=$price;
}
public function gethotelinfo(){
return $hotelinfo;
}
public function getprice(){
return $price;
}
}
And here is what I am attempting to do-
<?PHP
include 'file.php';
$hotelsdetail=array();
$hotelsdetail[0]=new hoteldetails();
$hotelsdetail[0].sethotelinfo($rs);
$hotelsdetail[0].setprice('150');
?>
The class attempting to create the array doesn't compile but is just a best guess as to how I can do this. Thanks again
What you should probably do is:
$hotelsDetail = array();
$details = new HotelDetails();
$details->setHotelInfo($rs);
$details->setPrice('150');
// assign it to the array here; you don't need the [0] index then
$hotelsDetail[] = $details;
In your specific case, the issue is that you should use ->, not .. The period isn't used in PHP to access attributes or methods of a class:
$hotelsdetail[0] = new hoteldetails();
$hotelsdetail[0]->sethotelinfo($rs);
$hotelsdetail[0]->setprice('150');
Note that I capitalized the class, object, and function names properly. Writing everything in lowercase is not considered good style.
As a side note, why is your price a string? It should be a number, really, if you ever want to do proper calculations with it.
You should append to your array, not assign to index zero.
$hotelsdetail = array();
$hotelsdetail[] = new hoteldetails();
This will append the object to the end of the array.
$hotelsdetail = array();
$hotelsdetail[] = new hoteldetails();
$hotelsdetail[] = new hoteldetails();
$hotelsdetail[] = new hoteldetails();
This would create an array with three objects, appending each one successively.
Additionally, to correctly access an objects properties, you should use the -> operator.
$hotelsdetail[0]->sethotelinfo($rs);
$hotelsdetail[0]->setprice('150');
You can get the array of object by encoding it into json and decoding it with $assoc flag as FALSE in json_decode() function.
See the following example:
$attachment_ids = array();
$attachment_ids[0]['attach_id'] = 'test';
$attachment_ids[1]['attach_id'] = 'test1';
$attachment_ids[2]['attach_id'] = 'test2';
$attachment_ids = json_encode($attachment_ids);
$attachment_ids = json_decode($attachment_ids, FALSE);
print_r($attachment_ids);
It would render an array of objects.
output:
Array
(
[0] => stdClass Object
(
[attach_id] => test
)
[1] => stdClass Object
(
[attach_id] => test1
)
[2] => stdClass Object
(
[attach_id] => test2
)
)

in_array() expects parameter 2 to be array

I have this idea of an multiarray with my files sorted into different groups/arrays.
Thinking it would be the easiest and most clean way to check what file we're inside, and should the navigation state be set to active on navigation tab 1,2 or 3?
I have this array;
Array
(
[home] => Array
(
[0] => index.php
[1] => something.php
)
[tour] => Array
(
[0] => tour.php
)
[tutorials] => Array
(
[0] => tutorials.php
)
)
The idea is, if i click on the home navigation button it goes to the index.php and a function checks whether it's the Home button that needs the active state, or the Tour button. In this case its the Home button.
[home] => Array
(
[0] => index.php
I made this function
function findNavigationActive($tap, $filename) {
if(in_array($filename, $topNavigationPages[$tap])) {
return 1;
}
return 0;
}
it should check, if index.php ($filename) is in the Home ($tap) array or navi-tap, then return 1. Unfortunately i get this error insted;
Warning: in_array() expects parameter 2 to be array, null given in /project/../../topNavigationHandler.php on line 21
What am I doing wrong?
FIXED
Used global $topNavigationPages; outside the function, and set $topNavigationPages values (array) beneath, and again used global $topNavigationPages inside the function to pull the array inside.
Thanks #tombs !
What this error means is that the second parameter isn't an array, therefore you can try something like this.:
if (is_array($topNavigationPages[$tap])) {
if(in_array($filename, $topNavigationPages[$tap])) {
return 1;
}
}
return 0;
You can do this without nesting the if loops by using a strict and operator.
Hope this helps
Note:
To resolve your scope issue you can use either a global value or a constant. To use a constant use the 'define' function, for a global declare the variable as such at the beginning of your file and in every subsequent function that you use it in. I strongly recommend using a constant.

Categories