PHP class to find value in array from session - php

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

Related

array_walk not changing value

function values($id,$col)
{
$vals = [1=>['name'=>'Lifting Heavy Boxes']];
return $vals[$id][$col];
}
$complete = [1=>["id"=>"2","sid"=>"35","material_completed"=>"1","date"=>"2017-12-18"]];
$form = 'my_form';
array_walk($complete, function(&$d,$k) use($form) {
$k = values($k, 'name').' ['.date('m/d/y',strtotime($d['date'])).'] ('.$form.')';
echo 'in walk '.$k."\n";
});
print_r($complete);
the echo outputs:
in walk Lifting Heavy Boxes [12/18/17] (my_form)
the print_r outputs:
Array
(
[1] => Array
(
[id] => 2
[sid] => 35
[material_completed] => 1
[date] => 2017-12-18
)
)
I have another array walk that is very similar that is doing just fine. The only difference I can perceive between them is in the one that's working, the value $d is already a string before it goes through the walk, whereas in the one that's not working, $d is an array that is converted to a string inside the walk (successfully, but ultimately unsuccessfully).
Something I'm missing?
And here's the fixed version:
array_walk($complete, function(&$d,$k) use($form) {
$d = values($k, 'name').' ['.date('m/d/y',strtotime($d['date'])).'] ('.$form.')';
});
That's what I was trying to do anyway. I wasn't trying to change the key. I was under the mistaken impression that to change the value you had to set the key to the new value.
You cannot change the key of the array inside the callback of array_walk():
Only the values of the array may potentially be changed; its structure cannot be altered, i.e., the programmer cannot add, unset or reorder elements. If the callback does not respect this requirement, the behavior of this function is undefined, and unpredictable.
This is also mentioned in the first comment:
It's worth nothing that array_walk can not be used to change keys in the array.
The function may be defined as (&$value, $key) but not (&$value, &$key).
Even though PHP does not complain/warn, it does not modify the key.

Yii2 array of objects, find the one

I have an array in yii2, and ocassionally it's only 1 single object that is not empty (all other element of array is empty) and I don't know which one is it. How can I either find the one that is not empty, or (my idea what I was trying), to create a new array, with array_filter (but I'm not sure if it works also with array of objects), to have only the one object in it.
if (count($ttepk) == 1) {
$ttep_filtered[] = array_filter($ttepk);
$id = $ttep_filtered[0]->id;
}
But it was also not working. I get the error message: PHP Notice – yii\base\ErrorException Trying to get property of non-object.
Before array_filter it looks like this:
Array
(
[3] => app\models\Model Object
(
after array_filter:
Array
(
[0] => Array
(
[3] => app\models\Model Object
(
So it seems, array_filter is not the one I need, or I use it the wrong way.
Can you please help me? Thank you!
You can try something like this
$filtered = array_filter($ttepk, function($item) {
return $item instanceof app\models\Model;
});
if (count($filtered) == 1) {
$id = reset($filtered)->id;
}

array_filter to check for conditions?

Can i use array_filter to check for specific conditions in a multidimensional array to replace an if() statement?
Want it to replace something like this:
if($item[0] == $key && $item[1] == "Test"){
//do something here....
}else{
//some other code here...
}
Current Array:
Array
(
[Zone] => Array
(
[Type] => s45
[packageA1] => Array
(
[level] => REMOVE FROM DB
[stage] => REMOVE FROM DB
[description] => description goes here
[image] => NULL
)
)
)
I want to search FIRST to see if [Type] exists. If it DOESN'T exist then i think ill use array_splice to insert it into the existing array. If it DOES exist then ill check if [packageA1] exists, if [packageA1] DOESN'T exist then i'll use array_splice once again. If [packageA1] DOES exist then ill skip over any type if inserting..
Does that make sense?
array_filter is designed for filtering arrays, not replacing boolean logic based on the contents of arrays.
array_filter takes 2 parameters - input and callback.
The callback function should take a single parameter (an item from the array) and return either true or false. The function returns an array with all of the items which returned false removed.
(If no callback function is specified, all items equal to false will be removed from the resulting array.)
Edit:
Based on your updated text, the below code should do what you want:
if (!$item['Zone']['Type']) {
$item['Zone']['Type'] = $something;
}
if (!$item['Zone']['packageA1']) {
!$item['Zone']['packageA1'] = $something;
}
Obviously you need to replace $something with what you actually want to add.
This code could be shortened by the use of ternary operators.
If you are running PHP 5.3 or greater you can do the following:
$item['Zone']['Type'] = $item['Zone']['Type'] ?: $something;
$item['Zone']['packageA1'] = $item['Zone']['packageA1'] ?: $something;
Prior to 5.3 you cannot miss out the middle of a ternary operation and have to use the full format as follows:
$value = conditon ? if_true : if_false;
(When using ?: as in my example, 'condition' and 'if_true' take the same value.)
The full ternary operator (for PHP prior to 5.3) would look like:
$item['Zone']['packageA1'] = $item['Zone']['packageA1'] ? $item['Zone']['packageA1'] : $something;

check is Array empty or not (php)

I am using Cakephp and try to customize the paginator result with some checkboxes .I was pass parameters in URL like this
"http://localhost/myproject2/browses/index/page:2/b.sonic:1/b.hayate:7/b.nouvo:2/b.others:-1/b.all:-2"
and cakephp translate URL to be the array like this
Array
(
[page] => 2
[b.sonic] => 1
[b.hayate] => 7
[b.nouvo] => 2
[b.others] => -1
[b.all] => -2
)
other time when I pass params without checking any checkbox.
"http://localhost/myproject2/browses/index/page:2"
and cakephp translate URL to be the array like this
Array
(
[page] => 2
)
how to simple check if [b.????] is available or not? I can't use !empty() function because array[page] is getting on the way.
If you want to check if a specific item is present, you can use either :
isset()
or array_key_exists()
But if you want to check if there is at least one item which has a key that starts with b. you will not have much choice : you'll have to loop over the array, testing each key.
A possible solution could look like this :
$array = array(
'page' => 'plop',
'b.test' => 150,
'b.glop' => 'huhu',
);
$found_item_b = false;
foreach (array_keys($array) as $key) {
if (strpos($key, 'b.') === 0) {
$found_item_b = true;
break;
}
}
if ($found_item_b) {
echo "there is at least one b.";
}
Another (possibly more fun, but not necessarily more efficient ^^ ) way would be to get the array of items which have a key that starts with b. and use count() on that array :
$array_b = array_filter(array_keys($array), function ($key) {
if (strpos($key, 'b.') === 0) {
return true;
}
return false;
});
echo count($array_b);
If page is always going to be there, you could simply do a count.
if (count($params) == 1) {
echo "There's stuff other than page!";
}
You could be more specific and check page is there and the count is one.
I think this is what you are looking for, the isset function so you would use it like...
if(isset(Array[b.sonic]))
{
//Code here
}

php determine position of array key relative to another key

I was wondering if it was possible to determine what position a key in an array is in relation to another key. I have a large multidimensional array and I need perform Function A when the key [E14_21] comes before [E14_20] and I need to perform a different Function B if not...
//perform Function A if:
[E14_20_0] => Array
(
[E14_21] => 3235
[E14_20] => 96
)
//Perform Function B if:
[E14_20_0] => Array
(
[E14_20] => 96
[E14_21] => 3235
)
You can do something like:
$keys = array_keys($E14_20_0);
if(array_search("E14_21", $keys) < array_search("E14_20", $keys)) {
// function A
} else {
// function B
}
You will of course need to add some sanity checks to make sure both keys exist in the array, etc.
It seems you might do this:
reset($E14_20_0);
first = each($E14_20_0);
second = each($E14_20_0);
if(first['key'] > second['key'])
{
//do something
}
This is very specific to your example, but it might help you get started.
reset() will reset the array pointer to the "first" element. each() returns the key and value of the array based on the pointer and advances the pointer. Then you can compare keys and perform your logic.

Categories