Check if all values of keys of multidimentionnal array are numeric? - php

i'm gona crazy, debuting in php..
I need to check if key value of an multidimentionnal array are all numeric..
a print_r() of my $values_arr give that:
Array ( [coco] => Array ( [0] => 18 [1] => 99 ) [chanel] => 150
I need to check if 18 and 99 and 150 are numeric, i will don't know what will in the array , and this array will not more 2 dimention.
I tryed many things, the last one..:
foreach ( $values_arr as $foo=>$bar ) {
if( !in_array( $foo, $_fields_arr ) || !is_numeric($bar ) ) {
echo "NOTGOOD";
}
}
****UPDATE****
new test :Here because chanel isnot int , this exemple should be echo "not goud",
but its not the case..
$_fields_arr = array('coco','chanel','other');
$ary = array(
'coco' => array(18, 99),
'chanel' => 'yu'
);
function allIntValues($o)
{
if (is_int($o)) return true;
if (is_array($o)){
foreach ($o as $k => $v) {
if (!is_int($v)) return false;
}
}
return true;
}
foreach ($ary as $k => $v) {
if (!in_array($k, $_fields_arr) || !#allIntValues($v)){
echo "notgood";
}
else echo "good";
}
thanks for any help,
regards

Update:
$ary = Array(
'coco' => array(18, 99),
'chanel' => 150
);
$_fields_arr = array('coco', 'chanel');
function allIntValues($o)
{
if (is_int($o)) return true;
if (is_array($o)){
foreach ($o as $k => $v) {
if (!is_int($v)) return false;
}
}
return true;
}
foreach ($ary as $k => $v) {
if (in_array($k, $_fields_arr) && #allIntValues($v)){
// $ary[$k] is no good
}
}
Assuming you want to test if all values are numeric (despite how deep the value's nested):
function is_numeric_array($ary)
{
foreach ($ary as $k => $v)
{
if (is_array($v))
{
if (!is_numeric_array($v))
return false;
}
else if (!is_numeric($v))
return false;
}
return true;
}
That will (recursively) check the array and make sure every value is numeric within the array.
array(1,2,3) // true
array('foo','bar','baz') // false ('foo', 'bar' & 'baz')
array(1,2,array(3,4)) // true
array(array(1,'foo'),2,3) // false (foo)
array("1,", "2.0", "+0123.45e6") // true

You are using the value instead of the key:
if( !in_array( $bar, $_fields_arr ) || !is_numeric($foo ) ) {

Related

array_filter not working for multi dimensional array

Here is the non-functional code. It does not return anything. Not quite sure what is wrong with the syntax I am using.
function findNeedle($array, $needle) {
return array_values(array_filter($array, function($arrayValue) use($needle) { return $arrayValue['lp_url'] == $needle; } ));
}
$myarray =
0 =>
array (
'lp_url' => 'http://example.com/nx/?utm_source=aa&utm_medium=referral',
'lp_term_id' => 1435949468,
'aff_term_id' => 1445295565,
'offer_term_id' => 1445295996,
),
1 =>
array (
'lp_url' => 'http://example.org/nx/?utm_source=aa&utm_medium=referral',
'lp_term_id' => 1435949468,
'aff_term_id' => 1445295559,
'offer_term_id' => 1445295989,
),
);
$needle = 'http://example.com/nx/?utm_source=aa&utm_medium=referral';
if (is_array($myarray)) {
foreach ($myarray as $value) {
if (is_array($value))
{
$x = findNeedle($value, $needle);
}
}
Extract an array of the data for the lp_url column and check for $needle:
if(in_array($needle, array_column($myarray, 'lp_url'))) {
echo "Found";
} else {
echo "Not found";
}

Search value in array from comma separated value in PHP

I have following array
Array
(
[0] => Array
(
[data] => PHP
[attribs] => Array
(
)
[xml_base] =>
[xml_base_explicit] =>
[xml_lang] =>
)
[1] => Array
(
[data] => Wordpress
[attribs] => Array
(
)
[xml_base] =>
[xml_base_explicit] =>
[xml_lang] =>
)
)
one varialbe like $var = 'Php, Joomla';
I have tried following but not working
$key = in_multiarray('PHP', $array,"data");
function in_multiarray($elem, $array,$field)
{
$top = sizeof($array) - 1;
$bottom = 0;
while($bottom <= $top)
{
if($array[$bottom][$field] == $elem)
return true;
else
if(is_array($array[$bottom][$field]))
if(in_multiarray($elem, ($array[$bottom][$field])))
return true;
$bottom++;
}
return false;
}
so want to check if any value in $var is exists in array(case insensitive)
How can i do it without loop?
This should work for you:
(Put a few comments in the code the explain whats goning on)
<?php
//Array to search in
$array = array(
array(
"data" => "PHP",
"attribs" => array(),
"xml_base" => "",
"xml_base_explicit" => "",
"xml_lang" => ""
),
array(
"data" => "Wordpress",
"attribs" => array(),
"xml_base" => "",
"xml_base_explicit" => "",
"xml_lang" => "Joomla"
)
);
//Values to search
$var = "Php, Joomla";
//trim and strtolower all search values and put them in a array
$search = array_map(function($value) {
return trim(strtolower($value));
}, explode(",", $var));
//function to put all non array values into lowercase
function tolower($value) {
if(is_array($value))
return array_map("tolower", $value);
else
return strtolower($value);
}
//Search needle in haystack
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;
}
//Search ever value in array
foreach($search as $value) {
if(in_array_r($value, array_map("tolower", array_values($array))))
echo $value . " found<br />";
}
?>
Output:
php found
joomla found
to my understanding , you are trying to pass the string ex : 'php' and the key : 'data' of the element .
so your key can hold a single value or an array .
$key = in_multiarray("php", $array,"data");
var_dump($key);
function in_multiarray($elem, $array,$field)
{
$top = sizeof($array) - 1;
$bottom = 0;
while($bottom <= $top)
{
if(is_array($array[$bottom][$field]))
{
foreach($array[$bottom][$field] as $value)
{
if(strtolower(trim($value)) == strtolower(trim($elem)))
{
return true;
}
}
}
else if(strtolower(trim($array[$bottom][$field])) == strtolower(trim($elem)))
{
return true;
}
$bottom++;
}
return false;
}

Recursive search return all keys where value is present

Currently stuck trying to get the last part working, wanting to get all array keys returned where the value exists.
Test data
$testArr = array(
'id' => '249653315914',
'title' => 'testing',
'description' => 'testing',
'usernames' => array('jake', 'liam', 'john'),
'masterNames' => array('jake'),
'data' => array(
'aliases' => array(
'jake'
)
)
);
Method
recursive_search('jake', $testArr);
function recursive_search($needle, $haystack, $child = false) {
$values = array();
foreach($haystack as $key => $value) {
$current_key = $key;
if($needle === $value OR (is_array($value) && $children = recursive_search($needle, $value, true) !== false)) {
if($child) {
if($needle == $value) {
return true;
}
echo "children: $child, current_key: $current_key ";
return $current_key;
}
echo "current_key: $current_key, key: $key <br>";
$values[] = $current_key;
}
}
if(!empty($values)) {
return $values;
}
return false;
}
Output
current_key: usernames, key: usernames
current_key: masterNames, key: masterNames
children: 1, current_key: aliases current_key: data, key: data
array (size=3)
0 => string 'usernames' (length=5)
1 => string 'masterNames' (length=8)
2 => string 'data' (length=4)
Expected
array(
'usernames',
'masterNames',
'data' => array('aliases')
)
I'm losing track on the $child part I think, somewhere I should be returning something and assigning it but I think I've looked at this to long and overlooking the obvious.
Any help is awesome.
$testArr = array(
'id' => '249653315914',
'title' => 'jake',
'description' => 'testing',
'usernames' => array('jake', 'liam', 'john'),
'masterNames' => array('jake'),
'data' => array(
'aliases' => array(
'jake'
),
'aliases2' => array('level3' => array('jake'))
)
);
function recursive_search($needle, $haystack) {
$return = array();
if (is_array($haystack))
foreach($haystack as $key => $value)
{
if (is_array($value))
{
$child = recursive_search($needle, $value);
if (is_array($child) && !empty($child))
$return = array_merge($return, array($key => $child));
elseif ($child) $return[] = $key;
}
elseif ($value === $needle)
if (is_integer($key))
return true;
else
$return[] = $key;
}
elseif ($haystack === $needle)
return true;
return $return;
}
Output
Array
(
[0] => title
[1] => usernames
[2] => masterNames
[data] => Array
(
[0] => aliases
[aliases2] => Array
(
[0] => level3
)
)
)
Testing is needed, no warranty that it will work in all cases. Also, in the cases like this array('level3' => array('jake'), 'jake'), it will not go deeper to level3 and so on, as 'jake' is present in the original array. Please mention if that is not a desired behavior.
Edit by Bankzilla: To work with objects
function recursive_search($needle, $haystack) {
$return = array();
if (is_array($haystack) || is_object($haystack)) {
foreach($haystack as $key => $value) {
if (is_array($value) || is_object($value)) {
$child = recursive_search($needle, $value);
if ((is_array($child) || is_object($child)) && !empty($child)) {
$return = array_merge($return, array($key => $child));
} elseif ($child) {
$return[] = $key;
}
}
elseif ($value === $needle) {
if (is_integer($key)) {
return true;
} else {
$return[] = $key;
}
}
}
} elseif ($haystack === $needle) {
return true;
}
return $return;
}
the things I thought you did wrong was checking for if current $value is an array and doing a recursive search on it, while doing nothing with the return value of it (which should be the array either false ) , here I used a more step by step approach (well at least I thought so )
this works for a "tree with more branches"
EDIT
function recursive_search($needle, $haystack) {
$values = array();
foreach($haystack as $key => $value) {
if(is_array($value)) {
$children = $this->recursive_search($needle, $value);
if($children !== false){
if(!is_bool($children) and !empty($children)){
$key = array($key => $children);
}
$values[] = $key;
}
} else if(strcmp($needle, $value) == 0 ){
if(is_int($key))
return true;
else
$vaues[] = $key;
}
}
if(!empty($values)) {
return $values;
}
return false;
}
got rid of the "0"s in the array, thx Cheery for the hint (from his response)

Check if specific array key exists in multidimensional array - PHP

I have a multidimensional array e.g. (this can be many levels deep):
$array = Array (
[21] => Array ( )
[24] => Array (
[22] => Array ( )
[25] => Array (
[26] => Array ( )
)
)
)
I am trying to loop through it to see if a certain key exists:
$keySearch = 22; // key searching for
function findKey($array, $keySearch) {
foreach ($array as $item){
if (isset($item[$keySearch]) && false === findKey($item[$keySearch], $item)){
echo 'yes, it exists';
}
}
}
findKey($array, $keySearch);
But it finds nothing. Is there an error in the loop?
array_key_exists() is helpful.
Then something like this:
function multiKeyExists(array $arr, $key) {
// is in base array?
if (array_key_exists($key, $arr)) {
return true;
}
// check arrays contained in this array
foreach ($arr as $element) {
if (is_array($element)) {
if (multiKeyExists($element, $key)) {
return true;
}
}
}
return false;
}
Working example: http://codepad.org/GU0qG5su
I played with your code to get it working :
function findKey($array, $keySearch)
{
foreach ($array as $key => $item) {
if ($key == $keySearch) {
echo 'yes, it exists';
return true;
} elseif (is_array($item) && findKey($item, $keySearch)) {
return true;
}
}
return false;
}
Here is a one line solution:
echo strpos(json_encode($array), $key) > 0 ? "found" : "not found";
This converts the array to a string containing the JSON equivalent, then it uses that string as the haystack argument of the strpos() function and it uses $key as the needle argument ($key is the value to find in the JSON string).
It can be helpful to do this to see the converted string: echo json_encode($array);
Be sure to enclose the needle argument in single quotes then double quotes because the name portion of the name/value pair in the JSON string will appear with double quotes around it. For instance, if looking for 22 in the array below then $key = '"22"' will give the correct result of not found in this array:
$array =
Array (
21 => Array ( ),
24 =>
Array (
522 => Array ( ),
25 =>
Array (
26 => Array ( )
)
)
);
However, if the single quotes are left off, as in $key = "22" then an incorrect result of found will result for the array above.
EDIT: A further improvement would be to search for $key = '"22":'; just incase a value of "22" exists in the array. ie. 27 => "22" In addition, this approach is not bullet proof. An incorrect found could result if any of the array's values contain the string '"22":'
function findKey($array, $keySearch)
{
// check if it's even an array
if (!is_array($array)) return false;
// key exists
if (array_key_exists($keySearch, $array)) return true;
// key isn't in this array, go deeper
foreach($array as $key => $val)
{
// return true if it's found
if (findKey($val, $keySearch)) return true;
}
return false;
}
// test
$array = Array (
21 => Array ( 24 => 'ok' ),
24 => Array (
22 => Array ( 29 => 'ok' ),
25 => Array (
26 => Array ( 32 => 'ok' )
)
)
);
$findKeys = Array(21, 22, 23, 24, 25, 26, 27, 28, 29, 30);
foreach ($findKeys as $key)
{
echo (findKey($array, $key)) ? 'found ' : 'not found ';
echo $key.'<br>';
}
returns false if doesn't exists, returns the first instance if does;
function searchArray( array $array, $search )
{
while( $array ) {
if( isset( $array[ $search ] ) ) return $array[ $search ];
$segment = array_shift( $array );
if( is_array( $segment ) ) {
if( $return = searchArray( $segment, $search ) ) return $return;
}
}
}
return false;
}
For sure some errors, is this roughly what you are after? (Untested code):
$keySearch=22; // key seraching for
function findKey($array, $keySearch)
{
// check whether input is an array
if(is_array($array)
{
foreach ($array as $item)
{
if (isset($item[$keySearch]) || findKey($item, $keysearch) === true)
{
echo 'yes, it exists';
return true;
}
}
}
}
Here is one solution that finds and return the value of the key in any dimension array..
function findValByKey($arr , $keySearch){
$out = null;
if (is_array($arr)){
if (array_key_exists($keySearch, $arr)){
$out = $arr[$keySearch];
}else{
foreach ($arr as $key => $value){
if ($out = self::findValByKey($value, $keySearch)){
break;
}
}
}
}
return $out;
}
I did modified to return value of searched key:
function findKeyInArray($array, $keySearch, &$value)
{
foreach ($array as $key => $item) {
if ($key === $keySearch) {
$value = $item;
break;
} elseif (is_array($item)) {
findKeyInArray($item, $keySearch,$value);
}
}
}
$timeZone = null;
findKeyInArray($request, 'timezone', $timeZone);

Return true/false on searching multidimensional array

I have the following multidimensional $array:
Array
(
[0] => Array
(
[domain] => example.tld
[type] => 2
)
[1] => Array
(
[domain] => other.tld
[type] => 2
)
[2] => Array
(
[domain] => blaah.tld
[type] => 2
)
)
I simply want to recursively search all the arrays on both key and value, and return true if the key/value was found or false if nothing was found.
Expected output:
search_multi_array($array, 'domain', 'other.tld'); // Will return true
search_multi_array($array, 'type', 'other.tld'); // Will return false
search_multi_array($array, 'domain', 'google.com'); // Will return false
I've figured out a ugly-ugly method to search against the domain against all keys with this function:
function search_multi_array($search_value, $the_array) {
if (is_array($the_array)) {
foreach ($the_array as $key => $value) {
$result = search_multi_array($search_value, $value);
if (is_array($result)) {
return true;
} elseif ($result == true) {
$return[] = $key;
return $return;
}
}
return false;
} else {
if ($search_value == $the_array) {
return true;
}
else
return false;
}
}
Can anyone do better and match both against the key and value in a more elegant way?
If it doesn't go beyond those 2 levels, flipping keys/merging makes life a lot more pleasant:
<?php
$data = array
(
'0' => array
(
'domain' => 'example.tld',
'type' => 2
),
'1' => array
(
'domain' => 'other.tld',
'type' => 2,
),
'2' => array
(
'domain' => 'blaah.tld',
'type' => 2
)
);
$altered = call_user_func_array('array_merge_recursive',$data);
var_dump($altered);
var_dump(in_array('other.tld',$altered['domain']));
var_dump(in_array('other.tld',$altered['type']));
var_dump(in_array('google.com',$altered['domain']));
To go beyond 2nd level, we have to loop once through all the nodes:
$option2 = array();
foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($data)) as $key => $value){
$option2[$key][] = $value;
}
var_dump($option2);
One way is to create a reverse mapping from [domain] => [indices] and from [type] => [indices]. It's probably not going to save you much unless you do lots of searches.
(hint: you probably want to wrap it into a class to prevent inconsistencies in the mappings)
also, anytime you see something like this:
if ($search_value == $the_array) {
return true;
} else {
return false;
}
you can always turn it into:
return $search_value == $the_array;
function search_mutli_array($SearchKey, $SearchValue, $Haystack)
{
$Result = false;
if (is_array($Haystack))
{
foreach ($Haystack as $Key => $Value)
{
if (is_array($Value))
{
if (search_mutli_array($SearchKey, $SearchValue, $Value))
{
$Result = true;
break;
}
}
else if ($SearchKey == $Key && $SearchValue == $Value)
{
$Result = true;
break;
}
}
}
return $Result;
}

Categories