I pull a list of permissions from a the DB using and put them into an array;
while($row = mysql_fetch_assoc($get_permissions)) {
$_SESSION['permissions'][] = $row;
}
The contents of the session variable then looks like this;
array(2) {
[0]=> array(1) {
["permission_name"] => string(15) "acl_assets_read"
}
[1]=> array(1) {
["permission_name"] => string(16) "acl_assets_write"
}
}
below is the output using print_r instead which makes it easier to read.
Array ( [0] => Array ( [permission_name] => acl_assets_read ) [1] => Array ( [permission_name] => acl_assets_write ) )
I've read about using array_search and think it should work. I've tried to use the following to search for a permission;
if (array_search('acl_assets_read', $_SESSION['permissions'])) {
echo "true";
}
The problem i have is that even though the result is there, it keep returning false. The syntax looks correct to me.
Your problem is that you add the entire row (which is an array of its own) from your database into the $_SESSION['permissions']-array, forming a sub-array for each time it iterates the values from the database.
This means that all values in $_SESSION['permissions'] are arrays, not strings. This in turn means that you cannot search for a string like that.
If you have stored the values you are interested in, in a column named permissions in the database, you simply need to add that element only to your $_SESSION['permissions']-array, like this
$_SESSION['permissions'][] = $row['permissions'];
This will add the string from that row into an element in the array $_SESSION['permissions'].
It's also worth noting that array_search() returns the key of the array, where as the first element will have an index (key) equal to 0. This means that the very first element of your array would really look like if (0) { /* code */ }. This will return to false (if (0) == false), so you should perhaps look into using ìn_array(), which returns a boolean true/false.
if (in_array('acl_assets_read', $_SESSION['permissions'])) {
echo "true";
}
Also, mysql_* functions are deprecated, and you shoud stop using them if you can.
array_search will work for you but you need the proper array to search.
Take a look at this:
$arrOne = array("one", "two");
$arrTwo = array(array("one"), array("two"));
$key = array_search("one", $arrOne);
var_dump($key); // int(0) is the index of where the value was found
$key = array_search("two", $arrTwo);
var_dump($key); // bool(false) because "two" != array("one") or array("two")
Notice that the second array_search will return false because a string does not equal an array.
If you had:
array(2) {
[0]=> string(15) "acl_assets_read"
[1]=> string(16) "acl_assets_write"
}
instead of:
array(2) {
[0]=> array(1) {
["permission_name"] => string(15) "acl_assets_read"
}
[1]=> array(1) {
["permission_name"] => string(16) "acl_assets_write"
}
}
then your array_search would find the proper string
Here is your answer :
$userdb = array(array("permission_name" => 'acl_assets_read'),array("permission_name" => 'acl_assets_write'));
$key = array_search("acl_assets_write", array_column($userdb, 'permission_name'));
if($key != ''){
echo 'true';
}
If needle found $key show key of needle. If needle is not found $key show blank.
Related
i build an array from mysql this way
$q="select account_code from chart_master;";
// Generate resultset
$result_set = $con->query($q);
$list = Array();
while( $myrow = mysqli_fetch_array($result_set) ) {
$list[] = $myrow;
}
when i dump $list i get:
array(79) { [0]=> array(2) { [0]=> string(8) "11011001" ["account_code"]=> string(8) "11011001" } [1]=> array(2) { [0]=> string(8) "11011002" ["account_code"]=> string(8) "11011002" } [2]=> array(2) { [0]=> string(8) "11011005" ["account_code"]=> string(8) "11011005" } ...
i now want to check if a value is found in the values 11011001, 11011002 etc with this code:
if (in_array($row['1'], $list))
{
echo $row['1']." found in the array";
}
with $row['1'] being one of the searched value.
I guess I am not looking at the right depth in the array because my in_array does not return anything.
Thoughts?
You should go through each element of your $list array and apply in_array to it.
foreach($list as $listItem){
if(in_array($row['1'], $listItem)){
echo $row['1']." found in the array";
}
}
in_array() only checks one dimension. That's why you need to go iterate through the first dimension and apply it to the second one.
The most succinct version of this I can imagine would be:
$exists = array_search('1001010101', array_column($list, 'account_code')) !== false;
This grabs the account_code column from the multidimensional array and looks inside that column for the value provided. If you only need an existence check, this seems to be a fast way of doing it.
However, if you don't need the rest of that SQL result set, I'd look into maybe doing a COUNT() or using a WHERE to narrow the result set instead. That would be more resource efficient.
This question already has answers here:
How to check if a specific value exists at a specific key in any subarray of a multidimensional array?
(17 answers)
Closed 4 years ago.
array(7) {
[0]=>
array(2) {
["name"]=>
string(14) "form[username]"
["value"]=>
string(1) "1"
}
[1]=>
array(2) {
["name"]=>
string(15) "form[is_active]"
["value"]=>
string(1) "1"
}
[2]=>
array(2) {
["name"]=>
string(8) "form[id]"
["value"]=>
string(1) "9"
}
}
I want to get the id from an array. The output I like to achive is 9.
My approach:
echo $array['form[id]'];
But I don't get an output.
When you use $array['form[id]']; you are looking for the key called 'form[id]' which will not work because the keys of your array are 0, 1 and 2. You can get your desired value by using $array[2]['value']. However this will always call the 2nd element of your array, which might not be what you want. A more dynamic solution would be something like this:
foreach ($array as $element) {
if ($element['name'] == 'form[id]') {
echo $element['value'];
break;
}
}
This will loop through your whole array and check the names of each element. Then when it matches your desired name it will print the value for that exact element.
The easiest way might be to just first re-index the array using array_column. Then you can use the name field as the key:
$array = array_column($array, null, 'name');
echo $arr['form[id]']['value'];
// 9
See https://3v4l.org/L1gLR
You could use a foreach and check for the content .. but the content for index 'name' is just a string form[id]
anyway
foreach( $myArray AS $key => $value){
if ($value['name'] == 'form[id]' ) {
echo $key;
echo $value;
}
}
You are trying to get the value as if it's an associative array (sometimes called a dictionary or map), however it's a plain or indexed array.
Get the value you want by calling $array[2]["value"]
You can also use some of the higher level functions such as array_search; then you could use:
$id = array_search(function($values) {
return $values['name'] == 'form[id]';
}, $array)["value"];
So I think you need to filter the array to find the element you need first, then output that element's value:
$filtered_array = array_filter($your_array, function(element){
return element['name'] == 'form[username]';
});
if (!empty($filtered_array)) {
echo array_pop($filtered_array)['value'];
}
I have an array like this:
array(2) {
[0]=> array(1) { ["cate_id"]=> string(2) "14" }
[1]=> array(1) { ["cate_id"]=> string(2) "15" }
}
How can I check if the value 14 exists in the array without using a for loop?
I've tried this code:
var_dump(in_array('14',$categoriesId));exit;
but it returns false, and I do not know why.
I wonder why you don't need a for. Well a quickest way would be to serialize your array and do a strpos.
$yourarray = array('200','3012','14');
if(strpos(serialize($yourarray),14)!==false)
{
echo "value exists";
}
Warning : Without using looping structures you cannot guarantee the value existence inside an array. Even an in_array uses internal looping structures. So as the comments indicate you will get a false positive if there is 1414 inside the $yourarray variable. That's why I made it a point in the first place.
If you need to find a specific value in an array. You have to loop it.
Do this :
var_dump(in_array("14",array_map('current',$categoriesId))); //returns true
So I'm using a foreach cycle like this:
foreach($cats_arr as $category) {
$options_arr[$category->name] = false;
}
and when I var_dump($options_arr['Articles']) it comes out like this, so I assume that I'm building the array properly:
bool(false) string(1) "5"
Next, I need to assign that array as a value of a key-value pair in another array, and then it breaks. I'm doing it like this:
$admin_options = array(
"cats" => $options_arr
);
So I can access the array with $admin_options['cats'], but how to I access the array's keys that's assigned to the "cats" key?
EDIT: Here's what comes out when I var_dump($admin_options['cats'])
array(1) { [0]=> array(4) { ["Articles"]=> bool(false) ["Blog Posts"]=> bool(false) ["News"]=> bool(false) ["Uncategorized"]=> bool(false) } }
Your $options_arr contains multiple keys, so you will have to either specify the key or use a foreach loop:
// Echo first key
echo $admin_options['cats'][0]['Articles'];
// Or this for all the keys
foreach($admin_options['cats'] as $cat) {
echo $cat['Articles'];
}
update
how can I retrieve this value? I need to do that if I will write the value to my database.
array(3) {
[1]=> NULL
[2]=> array(2) {
[123]=>
int(123)
[122]=>
int(0)
}
[3]=> NULL
}
There is something missing in your output. I assume it looks something like:
// var_dump($array);
array(1) {
[0]=>
string(2) "39"
}
so you can access the value with $array[0]. Simple array access.
As arrays are the most important data structure in PHP, you should learn how to deal with them.
Read PHP: Arrays.
Update:
Regarding your update, which value do you want? You have a multidimensional array. This is what you will get:
$array[1] // gives null
$array[2] // gives an array
$array[2][123] // gives the integer 123
$array[2][122] // gives the integer 0
$array[3] // gives null
Maybe you also want (have) to loop over the inner array to get all values:
foreach($array[2] as $key => $value) {
// do something with $key and $value
}
As I said, read the documentation, it contains everything you need to know. Accessing arrays in PHP is not much different than in other programming languages.
The PHP manual contains a lot of examples, it is a pretty could documentation. Use it!
If your array is referenced as $myArray, you can get the string 39 via $myArray[0], i.e., this zeroth item.