I have following arrays :
<?php
$a=array(
"abc"=>array("red","white","orange"),
"def"=>array("green","vilot","yellow"),
"xyz"=>array("blue","dark","pure")
);
echo array_search(array("dark"),$a);
?>
How to get output of xyz in array list.
array_search returns false or the key. Since you have multiple dimensions you must loop through to get the lowest level.
Since we are in another dimension your return will actually be 1. For this reason, if array_search succeeds we must use the key that is defined in the foreach
<?php
$a=array("abc"=>array("red","white","orange"),"def"=>array("green","vilot","yellow"),"xyz"=>array("blue","dark","pure"));
foreach($a as $key=>$data){
if(array_search("dark",$data)){
echo $key;
}
}
Outputs: xyz
You can create one user-define function to check value
$a=array("abc"=>array("red","white","orange"),"def"=>array("green","vilot","yellow"),"xyz"=>array("blue","dark","pure"));
function search_data($value, $array) {
foreach ($array as $key => $val) {
if(is_array($val) && in_array($value,$val))
{
return $key;
}
}
return null;
}
echo search_data("dark",$a);
DEMO
Please try this
function searchMultiArray($arrayVal,$val){
foreach($arrayVal as $key => $suba){
if (in_array($val, $suba)) {
return $key;
}
}
}
$a = array("abc"=>array("red","white","orange"),"def"=>array("green","vilot","yellow"),"xyz"=>array("blue","dark","pure"));
echo $keyVal = searchMultiArray($a , "dark");
Related
I need to get index of from array of objects without using loop as per the key name using PHP. Here I am explaining my code below.
$arr = array(array("name"=>"Jack","ID"=>10),array("name"=>"Jam","ID"=>11),array("name"=>"Joy","ID"=>12));
$key = array_search('Jack', $arr);
echo $key;exit;
Here my code does not give any output. By using some key name I need the index of that object present inside array and also I dont want to use any loop. I need Is ther any PHP in build method so that I can get the result directly.
$arr = array(array("name"=>"Jack","ID"=>10),array("name"=>"Jam","ID"=>11),array("name"=>"Joy","ID"=>12));
function myfunction($v){return $v['name'];}
echo array_search('Jack', array_map( 'myfunction', $arr ));
<?php
$arr = array(array("name"=>"Jack","ID"=>10),array("name"=>"Jam","ID"=>11),array("name"=>"Joy","ID"=>12));
//calling function searchByName
$key = searchByName('Jasck',$arr);
if($key != '-1'){
print_r($arr[$key]);
}else{
echo "No match found";
}
//function to chek if the name is there or not.
function searchByName($name, $array) {
foreach ($array as $key => $val) {
if ($val['name'] == $name) {
return $key;
}
}
return '-1';
}
sandbox
How can check that all keys are include sub key.
$array1 = array("key1"=>"sub1", "key2"=>"sub2"); // true
$array2 = array("key1", "key2"=>"sub2"); // false
$array3 = array("key1"=>"sub1", "key2"); // false
$array4 = array("key1", "key2"); // false
if(checkSubKey($array1))
echo "true";
else
echo "false";
Thanks so much.
You can also use foreach for this.
$flag=true;
foreach($arr as $key=>$value)
{
if(!($key && $value))
{
$flag= false;
break;
}
}
if($flag==false)
{
//your stuff
}
$array1 = array("key1"=>"sub1", "key2"=>"sub2");
$hasKey = true;
foreach ($array1 as $key => $value)
{
if(!is_string($key))
{
$hasKey = false;
}
}
var_dump($hasKey); //true
$array2 = array("key1", "key2"=>"sub2");
$hasKey = true;
foreach ($array2 as $key => $value)
{
if(!is_string($key))
{
$hasKey = false;
}
}
var_dump($hasKey); //false
This method will work provided you do not assign your own numeric keys. All array positions have an index. If you don't assign one, it will be numerical by default. This method takes advantage of that by assuming that if the array element doesn't have a string-based key, then its key is missing. Although not technically true, it's true enough to satisfy your example.
Try array_key_exists()
Return true if array has key or false if not.
if(array_key_exists("key",$yourarray))
{
echo "exists";
}
{
else "not exist";
}
In order to make sure that a particular key exists in an array, you can make use of php's array_key_exists method:
if (array_key_exists("key1", $array1))
{
echo "Key exists!";
}
You could make use of regular expressions as well, with a little difference though (using preg_match method):
foreach($array1 as $key=> $value){
if(preg_match("/^key/", $key)){ //regular expression
echo "this key exists";
}
}
Alternatively, if you want to determine whether a key holds an array itself (i.e. a sub-array), you could do the following:
foreach($array1 as $a){
if(is_array($a)){
//do some stuff on the inner array
}
}
I have an array where each element has a subarray with multiple Ids. When looping through the array, I'd like to check if the subarray has any elements besides a given one.
For example, I'd like to echo 'Yes' whenever one of the subarrays has any ids other than 'TESTID'.
I can do this by looping through the subarray, but I'd like to know of a way that doesn't require double loops.
Here's the current code:
foreach ($elements as $element) {
...
if (besidesInArray('TESTID',$element['ids'])) {
//operations
} else {
//element only has 'TESTID'
}
...
}
...
function besidesInArray($needle, $haystack) {
foreach ($haystack as $hay) {
if($hay != $needle) {
return TRUE;
}
}
return FALSE;
}
While this code works, I'd like to see if there's a more elegant solution.
You can use in_array() function to achieve this
foreach($array as $key => $subarray)
{
if(in_array("TESTID", $subarray))
{
//found
} else {
//not found
}
}
preg_grep for TESTID but invert the grep so that it returns entries NOT matching.
foreach($array as $subarray) {
if(preg_grep("/TESTID/", $subarray, PREG_GREP_INVERT)) {
echo 'Yes'; //others found
}
}
TESTID could be a var instead. Man I love some preg_grep!
find = implode(')|(',$mypatternarray);
find.="(".find.")";
foreach($subarray as $subar){
if(preg_match("find",$subar)>0)){
echo "id found";
}
}
I'm trying to find a part of a string in a multidimentional array.
foreach ($invitees as $invitee) {
if (in_array($invitee, $result)){
echo 'YES';
} else {
echo 'NO';
}
}
the $invitees array has 2 elements:
and $result is what I get from my Drupal database using db_select()
What I'm trying to do is, if the first part from one of the emails in $invitees is in $result it should echo "YES". (the part before the "#" charather)
For example:
"test.email" is in $result, so => YES
"user.one" is not in $result, so => NO
How do i do this? How can I search for a part of a string in a multidimentional array?
Sidenote: I noticed that the array I get from Drupal ($result) has 2 "Objects" which contain a "String", and not arrays like I would expect.
For example:
$test = array('red', 'green', array('apple', 'banana'));
Difference between $result and $test:
Does this have any effect on how I should search for my string?
Because $result is an array of objects, you'll need to use a method to access the value and compare it. So, for instance you could do:
//1: create new array $results from array of objects in $result
foreach ($result as $r) {
$results[] = get_object_vars($r);
}
//2: expanded, recursive in_array function for use with multidimensional arrays
function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
//3: check each element of the $invitees array
foreach ($invitees as $invitee) {
echo in_array_r($invitee, $results) ? "Yes" : "No";
}
Also, for some illumination, check out this answer.
You can search through the array using preg_grep, and use a wildcard for anything before and after it. If it returns a value (or values), use key to get the index of the first one. Then do a check if its greater than or equal to 0, which means it found a match :)
<?php
$array = array('test1#gdfgfdg.com', 'test2#dgdgfdg.com', 'test3#dfgfdgdfg');
$invitee = 'test2';
$result = key(preg_grep('/^.*'.$invitee.'.*/', $array));
if ($result >= 0) {
echo 'YES';
} else {
echo 'NO';
}
?>
Accepted larsAnders's answer since he pointed me in to direction of recursive functions.
This is what I ended up using (bases on his answer):
function Array_search($array, $string) {
foreach ($array as $key => $value) {
if (is_array($value)) {
Array_search($array[$key], $string);
} else {
if ($value->data == $string) {
return TRUE;
}
}
}
return FALSE;
}
I am trying to check if a value is in an array. If so, grab that array value and do something with it. How would this be done?
Here's an example of what I'm trying to do:
$the_array = array("buejcxut->10", "jueofi31->20", "nay17dtt->30");
if (in_array('20', $the_array)) {
// If found, assign this value to a string, like $found = 'jueofi31->20'
$found_parts = explode('->', $found);
echo $found_parts['0']; // This would echo "jueofi31"
}
This should do it:
foreach($the_array as $key => $value) {
if(preg_match("#20#", $value)) {
$found_parts = explode('->', $value);
}
echo $found_parts[0];
}
And replace "20" by any value you want.
you might be better off checking it in a foreach loop:
foreach ($the_array as $key => $value) {
if ($value == 20) {
// do something
}
if ($value == 30) {
//do something else
}
}
also you array definitition is strange, did you mean to have:
$the_array = array("buejcxut"=>10, "jueofi31"=>20, "nay17dtt"=>30);
using the array above the $key is the element key (buejcxut, jueofi31, etc) and $value is the value of that element (10, 20, etc).
Here's an example of how you can search the values of arrays with Regular Expressions.
<?php
$the_array = array("buejcxut->10", "jueofi31->20", "nay17dtt->30");
$items = preg_grep('/20$/', $the_array);
if( isset($items[1]) ) {
// If found, assign this value to a string, like $found = 'jueofi31->20'
$found_parts = explode('->', $items[1]);
echo $found_parts['0']; // This would echo "jueofi31"
}
You can see a demo here: http://codepad.org/XClsw0UI
if you want to define an indexed array it should be like this:
$my_array = array("buejcxut"=>10, "jueofi31"=>20, "nay17dtt"=>30);
then you can use in_array
if (in_array("10", $my_array)) {
echo "10 is in the array";
// do something
}