Related
I am trying to solve this problem to learn logic formulations, but this one's really taken too much of my time already.
Rules are simple, No loops and no built in PHP functions (eg. print_r, is_array.. etc).
This is what I have come up with so far.
function displayArray(array $inputArray, $ctr = 0, $tempArray = array()) {
//check if array is equal to temparray
if($inputArray != $tempArray) {
// check if key is not empty and checks if they are not equal
if($inputArray[$ctr]) {
// set current $tempArray key equal to $inputArray's corresponding key
$tempArray[$ctr] = $inputArray[$ctr];
if($tempArray[$ctr] == $inputArray[$ctr]) {
echo $tempArray[$ctr];]
}
$ctr++;
displayArray($inputArray, $ctr);
}
}
}
This program outputs this:
blackgreen
The problem starts when it reaches the element that is an array
$array = array(
'black',
'green',
array(
'purple',
'orange'
)
);
displayArray($array);
Any tips?
This what the return value is supposed to be: blackgreenpurpleorange
This was fun. I decided to make it work with most data types while I was at it. Just don't throw it any objects or nulls and things should work.
No more # error suppression. Now returns the string instead of echoing it.
I realized too late that isset() is actually a language construct rather than a function, and went with a null termination strategy to determine the end of the arrays.
function concatinateRecursive($array, $i = 0) {
static $s = '';
static $depth = 0;
if ($i == 0) $depth++;
// We reached the end of this array.
if ($array === NULL) {
$depth--;
return true;
}
if ($array === array()) return false; // empty array
if ($array === '') return false; // empty string
if (
$array === (int)$array || // int
$array === (float)$array || // float
$array === true || // true
$array === false || // false
$array === "0" || // "0"
$array == "1" || // "1" "1.0" etc.
(float)$array > 1 || // > "1.0"
(int)$array !== 1 // string
)
{
$s .= "$array";
return false;
}
// Else we've got an array. Or at least something we can treat like one. I hope.
$array[] = NULL; // null terminate the array.
if (!concatinateRecursive($array[$i], 0, $s)) {
$depth--;
return concatinateRecursive($array, ++$i, $s);
}
if ($depth == 1) {
return $s;
}
}
$array = array(
'black',
'green',
array(
'purple',
'orange'
)
);
echo concatinateRecursive($array);
blackgreenpurpleorange
Live demo
What about this? You must check if it is array or not.
function display_array(&$array, $index=0) {
if (count($array)<=$index) return;
if (is_array($array[$index])) {
echo '[ ';
display_array($array[$index]);
echo '] ';
}
else
echo "'" . $array[$index] . "' ";
display_array($array, $index+1);
}
// Try:
// $a = ['black', 'green', ['purple', 'orange'], 'beer', ['purple', ['purple', 'orange']]];
// display_array($a);
// Output:
// 'black' 'green' [ 'purple' 'orange' ] 'beer' [ 'purple' [ 'purple' 'orange' ] ]
try this have to use some inbuilt function like isset and is_array but its a complete working recursive method without using loop.
function displayArray(array $inputArray, $ctr = 0) {
if(isset($inputArray[$ctr]))
{
if(is_array($inputArray[$ctr]))
{
return displayArray($inputArray[$ctr]);
}
else
{
echo $inputArray[$ctr];
}
}
else
{
return;
}
$ctr++;
displayArray($inputArray, $ctr);
}
$array = array(
'black',
'green',
array(
'purple',
'orange'
)
);
displayArray($array);
OUTPUT :
blackgreenpurpleorange
DEMO
complete answer
$myarray = array(
'black',
'green',
array(
'purple',
'orange'
)
);
function printAll($a) {
if (!is_array($a)) {
echo $a, ' ';
return;
}
foreach($a as $k => $value) {
if($k<10){
//printAll($k);
printAll($value);
}
}
}
printAll($myarray);
This question already has answers here:
Filter multidimensional array based on partial match of search value
(3 answers)
Native function to filter array by prefix
(6 answers)
Closed 1 year ago.
I have an array and I'd like to search for the string 'green'. So in this case it should return the $arr[2]
$arr = array(0 => 'blue', 1 => 'red', 2 => 'green string', 3 => 'red');
is there any predefined function like in_array() that does the job rather than looping through it and compare each values?
For a partial match you can iterate the array and use a string search function like strpos().
function array_search_partial($arr, $keyword) {
foreach($arr as $index => $string) {
if (strpos($string, $keyword) !== FALSE)
return $index;
}
}
For an exact match, use in_array()
in_array('green', $arr)
You can use preg_grep function of php. It's supported in PHP >= 4.0.5.
$array = array(0 => 'blue', 1 => 'red', 2 => 'green string', 3 => 'red');
$m_array = preg_grep('/^green\s.*/', $array);
$m_array contains matched elements of array.
There are several ways...
$arr = array(0 => 'blue', 1 => 'red', 2 => 'green string', 3 => 'red');
Search the array with a loop:
$results = array();
foreach ($arr as $value) {
if (strpos($value, 'green') !== false) { $results[] = $value; }
}
if( empty($results) ) { echo 'No matches found.'; }
else { echo "'green' was found in: " . implode('; ', $results); }
Use array_filter():
$results = array_filter($arr, function($value) {
return strpos($value, 'green') !== false;
});
In order to use Closures with other arguments there is the use-keyword. So you can abstract it and wrap it into a function:
function find_string_in_array ($arr, $string) {
return array_filter($arr, function($value) use ($string) {
return strpos($value, $string) !== false;
});
}
$results = find_string_in_array ($arr, 'green');
if( empty($results) ) { echo 'No matches found.'; }
else { echo "'green' was found in: " . implode('; ', $results); }
Here's a working example: http://codepad.viper-7.com/xZtnN7
PHP 5.3+
array_walk($arr, function($item, $key) {
if(strpos($item, 'green') !== false) {
echo 'Found in: ' . $item . ', with key: ' . $key;
}
});
for search with like as sql with '%needle%' you can try with
$input = preg_quote('gree', '~'); // don't forget to quote input string!
$data = array(
1 => 'orange',
2 => 'green string',
3 => 'green',
4 => 'red',
5 => 'black'
);
$result = preg_filter('~' . $input . '~', null, $data);
and result is
{
"2": " string",
"3": ""
}
function check($string)
{
foreach($arr as $a) {
if(strpos($a,$string) !== false) {
return true;
}
}
return false;
}
A quick search for a phrase in the entire array might be something like this:
if (preg_match("/search/is", var_export($arr, true))) {
// match
}
function findStr($arr, $str)
{
foreach ($arr as &$s)
{
if(strpos($s, $str) !== false)
return $s;
}
return "";
}
You can change the return value to the corresponding index number with a little modification if you want, but since you said "...return the $arr[2]" I wrote it to return the value instead.
In order to find out if UTF-8 case-insensitive substring is present in array, I found that this method would be much faster than using mb_strtolower or mb_convert_case:
Implode the array into a string: $imploded=implode(" ", $myarray);.
Convert imploded string to lowercase using custom function:
$lowercased_imploded = to_lower_case($imploded);
function to_lower_case($str)
{
$from_array=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","Ä","Ö","Ü","Õ","Ž","Š"];
$to_array=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","ä","ö","ü","õ","ž","š"];
foreach($from_array as $key=>$val){$str=str_replace($val, $to_array[$key], $str);}
return $str;
}
Search for match using ordinary strpos: if(strpos($lowercased_imploded, "substring_to_find")!==false){do something}
This is a function for normal or multidimensional arrays.
Case in-sensitive
Works for normal arrays and multidimentional
Works when finding full or partial stings
Here's the code (version 1):
function array_find($needle, array $haystack, $column = null) {
if(is_array($haystack[0]) === true) { // check for multidimentional array
foreach (array_column($haystack, $column) as $key => $value) {
if (strpos(strtolower($value), strtolower($needle)) !== false) {
return $key;
}
}
} else {
foreach ($haystack as $key => $value) { // for normal array
if (strpos(strtolower($value), strtolower($needle)) !== false) {
return $key;
}
}
}
return false;
}
Here is an example:
$multiArray = array(
0 => array(
'name' => 'kevin',
'hobbies' => 'Football / Cricket'),
1 => array(
'name' => 'tom',
'hobbies' => 'tennis'),
2 => array(
'name' => 'alex',
'hobbies' => 'Golf, Softball')
);
$singleArray = array(
0 => 'Tennis',
1 => 'Cricket',
);
echo "key is - ". array_find('cricket', $singleArray); // returns - key is - 1
echo "key is - ". array_find('cricket', $multiArray, 'hobbies'); // returns - key is - 0
For multidimensional arrays only - $column relates to the name of the key inside each array.
If the $needle appeared more than once, I suggest adding onto this to add each key to an array.
Here is an example if you are expecting multiple matches (version 2):
function array_find($needle, array $haystack, $column = null) {
$keyArray = array();
if(is_array($haystack[0]) === true) { // for multidimentional array
foreach (array_column($haystack, $column) as $key => $value) {
if (strpos(strtolower($value), strtolower($needle)) !== false) {
$keyArray[] = $key;
}
}
} else {
foreach ($haystack as $key => $value) { // for normal array
if (strpos(strtolower($value), strtolower($needle)) !== false) {
$keyArray[] = $key;
}
}
}
if(empty($keyArray)) {
return false;
}
if(count($keyArray) == 1) {
return $keyArray[0];
} else {
return $keyArray;
}
}
This returns the key if it has just one match, but if there are multiple matches for the $needle inside any of the $column's then it will return an array of the matching keys.
Hope this helps :)
I have a multidimensional array like this
$array['value'][1][1]
Now i would like to implement if loop like this
if ($value = $array['value'][1][1]) {
echo "It works";
}
Now it works if i assign the values like [1][1],[2][1].
Is it possible to compare the whole array.
I mean if the array looks like
array[value][1][1],array[value][2][1],..........,array[value][n][1]
It works should be echoed.
I tried like this.
if ($value = $array['value'][][]) {
echo "It works";
}
But its not working. Can anyone give me the correct syntax?
I'm not sure if this is what you're looking for but you could try this function
$value is 1 in your case
function($array,$value)
foreach($array['amazon'] as $val){
if($value != $val[1])return FALSE;
}
return TRUE;
}
The function runs through $array['amazon'][*] and checks condition for each value. If found FALSE for any it returns
Based on your comments of what you're trying to accomplish, I think the following may solve your dilemma. Let me know if I'm going the wrong direction with this or have any additional questions/concerns.
<?php
$forms = array(
'amazon' => array(
0 => array(
1 => 111,
),
1 => array(
1 => 222,
),
2 => array(
1 => 333
)
)
);
$value = 333;
$it_works = False;
foreach($forms['amazon'] as $array) {
if($array[1] == $value) {
$it_works = True;
break;
}
}
if($it_works === True) {
print 'It Works!';
}
?>
You can try this:
$itWorks = true;
for( $a = 0; $a < sizeof( $array[value] ); $a ++ ){
if ( $value != $array[value][$a][1] ){
$itWorks = false;
break;
}
}
if( $itWorks ){
echo "It works";
}
Of course you must replace [value] with a legitimate value
function check() {
for($i = 0; $i < count($array[$value]); $i++) {
if($value != $array[$value][$i][1])
return FALSE;
}
echo 'It works!';
}
How can I check an array recursively for empty content like this example:
Array
(
[product_data] => Array
(
[0] => Array
(
[title] =>
[description] =>
[price] =>
)
)
[product_data] => Array
(
[1] => Array
(
[title] =>
[description] =>
[price] =>
)
)
)
The array is not empty but there is no content. How can I check this with a simple function?
Thank!!
function is_array_empty($InputVariable)
{
$Result = true;
if (is_array($InputVariable) && count($InputVariable) > 0)
{
foreach ($InputVariable as $Value)
{
$Result = $Result && is_array_empty($Value);
}
}
else
{
$Result = empty($InputVariable);
}
return $Result;
}
If your array is only one level deep you can also do:
if (strlen(implode('', $array)) == 0)
Works in most cases :)
Solution with array_walk_recursive:
function empty_recursive($value)
{
if (is_array($value)) {
$empty = TRUE;
array_walk_recursive($value, function($item) use (&$empty) {
$empty = $empty && empty($item);
});
} else {
$empty = empty($value);
}
return $empty;
}
Assuming the array will always contain the same type of data:
function TestNotEmpty($arr) {
foreach($arr as $item)
if(isset($item->title) || isset($item->descrtiption || isset($item->price))
return true;
return false;
}
Short circuiting included.
function hasValues($input, $deepCheck = true) {
foreach($input as $value) {
if(is_array($value) && $deepCheck) {
if($this->hasValues($value, $deepCheck))
return true;
}
elseif(!empty($value) && !is_array($value))
return true;
}
return false;
}
Here's my version. Once it finds a non-empty string in an array, it stops. Plus it properly checks on empty strings, so that a 0 (zero) is not considered an empty string (which would be if you used empty() function). By the way even using this function just for strings has proven invaluable over the years.
function isEmpty($stringOrArray) {
if(is_array($stringOrArray)) {
foreach($stringOrArray as $value) {
if(!isEmpty($value)) {
return false;
}
}
return true;
}
return !strlen($stringOrArray); // this properly checks on empty string ('')
}
If anyone stumbles on this question and needs to check if the entire array is NULL, meaning that each pair in the array is equal to null, this is a handy function. You could very easily modify it to return true if any variable returns NULL as well. I needed this for a certain web form where it updated users data and it was possible for it to come through completely blank, therefor not needing to do any SQL.
$test_ary = array("1"=>NULL, "2"=>NULL, "3"=>NULL);
function array_empty($ary, $full_null=false){
$null_count = 0;
$ary_count = count($ary);
foreach($ary as $value){
if($value == NULL){
$null_count++;
}
}
if($full_null == true){
if($null_count == $ary_count){
return true;
}else{
return false;
}
}else{
if($null_count > 0){
return true;
}else{
return false;
}
}
}
$test = array_empty($test_ary, $full_null=true);
echo $test;
$arr=array_unique(array_values($args));
if(empty($arr[0]) && count($arr)==1){
echo "empty array";
}
Returns TRUE if passed a variable other than an array, or if any of the nested arrays contains a value (including falsy values!). Returns FALSE otherwise.
Short circuits.
function has_values($var) {
if (is_array($var)) {
if (empty($var)) return FALSE;
foreach ($var as $val) {
if(has_values($val)) return TRUE;
}
return FALSE;
}
return TRUE;
}
Here's a good utility function that will return true (1) if the array is empty, or false (0) if not:
function is_array_empty( $mixed ) {
if ( is_array($mixed) ) {
foreach ($mixed as $value) {
if ( ! is_array_empty($value) ) {
return false;
}
}
} elseif ( ! empty($mixed) ) {
return false;
}
return true;
}
For example, given a multidimensional array:
$products = array(
'product_data' => array(
0 => array(
'title' => '',
'description' => null,
'price' => '',
),
),
);
You'll get a true value returned from is_array_empty(), since there are no values set:
var_dump( is_array_empty($products) );
View this code interactively at: http://codepad.org/l2C0Efab
I needed a function to filter an array recursively for non empty values.
Here is my recursive function:
function filterArray(array $array, bool $keepNonArrayValues = false): array {
$result = [];
foreach ($array as $key => $value) {
if (is_array($value)) {
$value = $this->filterArray($value, $keepNonArrayValues);
}
// keep non empty values anyway
// otherwise only if it is not an array and flag $keepNonArrayValues is TRUE
if (!empty($value) || (!is_array($value) && $keepNonArrayValues)) {
$result[$key] = $value;
}
}
return array_slice($result, 0)
}
With parameter $keepNonArrayValues you can decide if values such 0 (number zero), '' (empty string) or false (bool FALSE) shout be kept in the array. In other words: if $keepNonArrayValues = true only empty arrays will be removed from target array.
array_slice($result, 0) has the effect that numeric indices will be rearranged (0..length-1).
Additionally, after filtering the array by this function it can be tested with empty($filterredArray).
I'm looking for some tool to give me a recursive diff of two arrays. What I envision is a web page with two color-coded tree-structures. On each tree, green are parts of the array which match in both arrays, and red is for parts of each that don't match the other. Something like the output of dBug
I have some code that gives me a nested array to populate a report. I'm developing a new method that should be faster, but I need to test the values and also the structure, to make sure it gives output identical to the old method.
Is there something out there that I can use? Or do I need to write this? Or is there another way to accomplish my goals?
There is one such function implemented in the comments of array_diff.
function arrayRecursiveDiff($aArray1, $aArray2) {
$aReturn = array();
foreach ($aArray1 as $mKey => $mValue) {
if (array_key_exists($mKey, $aArray2)) {
if (is_array($mValue)) {
$aRecursiveDiff = arrayRecursiveDiff($mValue, $aArray2[$mKey]);
if (count($aRecursiveDiff)) { $aReturn[$mKey] = $aRecursiveDiff; }
} else {
if ($mValue != $aArray2[$mKey]) {
$aReturn[$mKey] = $mValue;
}
}
} else {
$aReturn[$mKey] = $mValue;
}
}
return $aReturn;
}
The implementation only handles two arrays at a time, but I do not think that really posses a problem. You could run the diff sequentially if you need the diff of 3 or more arrays at a time. Also this method uses key checks and does a loose verification.
The accepted answer is close to correct, but it doesn't really emulate array_diff correctly.
There are two problems that largely revolve around key matching:
array_diff has a specific behavior where it does not produce a result for an array key that is completely missing from the second array if its value is still in the second array. If you have two arrays $first = ['foo' => 2, 'moo' => 2] and $second = ['foo' => 2], using the accepted answer's function the output will be ['moo' => 2]. If you run the same arrays through array_diff, it will produce an empty array. This is because the above function's final else statement adds it to the diff if the array key is missing, but that's not the expected behavior from array_diff. The same is true with these two arrays: $first = ['foo' => 1] and $second = [1]. array_diff will produce an empty array.
If two arrays have the same values but different keys, it returns more values than expected. If you have two arrays $foo = [1, 2] and $moo = [2, 1], the function from the accepted answer will output all values from $foo. This is because it's doing a strict key matching on each iteration where it finds the same key (numerical or otherwise) in both arrays instead of checking all of the other values in the second array.
The following function is similar, but acts more closely to how you'd expect array_diff to work (also with less silly variable names):
function array_diff_recursive($arr1, $arr2)
{
$outputDiff = [];
foreach ($arr1 as $key => $value)
{
//if the key exists in the second array, recursively call this function
//if it is an array, otherwise check if the value is in arr2
if (array_key_exists($key, $arr2))
{
if (is_array($value))
{
$recursiveDiff = array_diff_recursive($value, $arr2[$key]);
if (count($recursiveDiff))
{
$outputDiff[$key] = $recursiveDiff;
}
}
else if (!in_array($value, $arr2))
{
$outputDiff[$key] = $value;
}
}
//if the key is not in the second array, check if the value is in
//the second array (this is a quirk of how array_diff works)
else if (!in_array($value, $arr2))
{
$outputDiff[$key] = $value;
}
}
return $outputDiff;
}
function array_diff_assoc_recursive($array1, $array2)
{
foreach($array1 as $key => $value){
if(is_array($value)){
if(!isset($array2[$key]))
{
$difference[$key] = $value;
}
elseif(!is_array($array2[$key]))
{
$difference[$key] = $value;
}
else
{
$new_diff = array_diff_assoc_recursive($value, $array2[$key]);
if($new_diff != FALSE)
{
$difference[$key] = $new_diff;
}
}
}
elseif((!isset($array2[$key]) || $array2[$key] != $value) && !($array2[$key]===null && $value===null))
{
$difference[$key] = $value;
}
}
return !isset($difference) ? 0 : $difference;
}
Example:
$a = array(
"product_a" => array(
'description'=>'Product A',
'color'=>'Red',
'quantity'=>'5',
'serial'=>array(1,2,3)
),
"product_b" => array(
'description'=>'Product B'
)
);
$b = array(
"product_a" => array(
'description'=>'Product A',
'color'=>'Blue',
'quantity'=>'5',
'serial'=>array(1,2,5)
),
"product_b" => array(
'description'=>'Product B'
)
);
Output:
array_diff_assoc_recursive($a,$b);
Array
(
[product_a] => Array
(
[color] => Red
[serial] => Array
(
[2] => 3
)
)
)
Try this code:
function arrayDiffRecursive($firstArray, $secondArray, $reverseKey = false)
{
$oldKey = 'old';
$newKey = 'new';
if ($reverseKey) {
$oldKey = 'new';
$newKey = 'old';
}
$difference = [];
foreach ($firstArray as $firstKey => $firstValue) {
if (is_array($firstValue)) {
if (!array_key_exists($firstKey, $secondArray) || !is_array($secondArray[$firstKey])) {
$difference[$oldKey][$firstKey] = $firstValue;
$difference[$newKey][$firstKey] = '';
} else {
$newDiff = arrayDiffRecursive($firstValue, $secondArray[$firstKey], $reverseKey);
if (!empty($newDiff)) {
$difference[$oldKey][$firstKey] = $newDiff[$oldKey];
$difference[$newKey][$firstKey] = $newDiff[$newKey];
}
}
} else {
if (!array_key_exists($firstKey, $secondArray) || $secondArray[$firstKey] != $firstValue) {
$difference[$oldKey][$firstKey] = $firstValue;
$difference[$newKey][$firstKey] = $secondArray[$firstKey];
}
}
}
return $difference;
}
$differences = array_replace_recursive(
arrayDiffRecursive($firstArray, $secondArray),
arrayDiffRecursive($secondArray, $firstArray, true)
);
var_dump($differences);
The answer by Mohamad is working good, except that it needs change on the line:
$difference[$newKey][$firstKey] = $secondArray[$firstKey];
with:
$difference[$newKey][$firstKey] = array_key_exists($firstKey, $secondArray) ? $secondArray[$firstKey] : null;
or, if you are using Laravel, with:
$difference[$newKey][$firstKey] = array_get($secondArray, $firstKey);
Otherwise, you will get errors like
PHP error: Undefined index: some_key
when a some_key exists in $secondArray but not in $firstArray