Check value of two-dimensional array in php - php

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

Related

Search an array stored in a Session

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.

PHP Convert array element to string prints "Array"

I query a database to obtain an array of results.
$usersArray = $db->getAllUsers(); // db-Query
If I print out the array's var_dump, its content is structured in form of other arrays:
array(9) { [0]=> **array**(1) { ["column"]=> string(20) "..." } [1]=> **array**(1) { ["column"] (remaining 8 are the same).
Now I need these values (which are correct, so far) to be casted as strings, so that:
array(9) { [0]=> **string**(1) { ["column"]=> string(20) "..." } [1]=> **string**(1) { ["column"] ....
There are several answers to this here and elsewhere, such as
-array_map: here I can actually cast the content as string, but- it prints "Array" instead the value. It tried then getting the content via
$users = array_map('strval',implode( $usersArray));
$users = array_map('strval', print_r($usersArray));
Neither of those worked.
Is there a method through which I could cast the content as string and get the content ? Or should I rewrite the query to format the result as strings ?
You have a wrong understanding of types or at least this:
array(9) { [0]=> **string**(1) { ["column"]=> string(20) "..." } [1]=> **string**(1) { ["column"] ....
doesn't make any sense. You believe you want elements to be of type string but yet contain array data which really doesn't work.
What you actually want is a different array structure but you are heading in the wrong direction for that.
You basically have two options:
Modify the getAllUsers() method in a way that returns your data in a structure you actually need.
Modify the data after you have received it. Obviously there's no builtin function convert_data_to_how_i_want_them() - so a basic understanding of arrays is required.
Basically you create a new array and copy those values you need to the position you need them at.
Something like this should do the trick in this case:
$out = array();
foreach($in as => $value) {
$out[] = $value['column'];
}

ksort function dont work in smarty PHP

i am trying to ksort an array, it worked when i was working with php, but i tried this in smarty template it didnt worked..
i tried like this
{{ksort($var)}}
but it returned this bool value and it even prints it..
1
actual array in $var is
array(1) { [1]=> array(2) { ["Name"]=> NULL ["SubMenu"]=> array(1) { [1]=> array(1) { ["SubName"]=> NULL } } } }
I have even tried {{$var = ksort($var)}} but it just store that bool value.
any ideas how to ksort this array in smarty??
According to the documentation ksort() always returns a boolean and the array is modified by reference.
You could assign the result of ksort() to a unused variable and use the array for your output like this.
{$tmp = ksort($var)}
{$var}

Array Key:Value Not Outputting Element Name

I'm creating an array from a database and its being created correctly as seen below.
array(2) {
["members"]=> bool(true)
["maps"]=> bool(true)
}
The issue is when I output the array using key:value the key is outputting the element number for example 0 for 'members and 1 for 'maps'.
foreach($vPrivileges as $vKey => $vValue) {
echo "$vKey: $vValue";
}
I need to output the actual name of the element and the value, I've spent awhile looking online and trying out some code samples but haven't been able to find a solution, any help is greatly appreciated.
Also I noticed that if I take the array and use the sort() function on it, it sorts as expected with one exception that it renames all the array elements to 0, 1 etc.
array(2) {
[0]=> bool(true)
[1]=> bool(true)
}
Use asort instead of sort to preserve array keys. This will fix your problem (assuming you call sort before the foreach-loop).

Get value from a array

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.

Categories