Check if an array is multi-dimensional [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Checking if array is multidimensional or not?
How do I check whether an array is multidimensional or not in PHP?

Use count twice, one with single parameter, and one with recursive mode
if (count($myarray) == count($myarray, COUNT_RECURSIVE))
{
echo 'MyArray is not multidimensional';
}
else
{
echo 'MyArray is multidimensional';
}
count(array,mode)
array ---Required. Specifies the array or object to count.
mode ---Optional. Specifies the mode of the function. Possible values:
0 - Default. Does not detect multidimensional arrays (arrays within arrays)
1 - Detects multidimensional arrays
Note: This parameter was added in PHP 4.2

Multi-dimensional arrays in PHP are simply arrays containing arrays. So a simple function for this could be written as
function is_multidim_array($arr) {
if (!is_array($arr))
return false;
foreach ($arr as $elm) {
if (!is_array($elm))
return false;
}
return true;
}
This will run through every element of $arr and check whether it's an array. Should it encounter an element that is not an array, it will return false. Otherwise, return true.

Related

Passing array reference to function PHP [duplicate]

This question already has answers here:
How to filter an array by a condition
(9 answers)
Closed 1 year ago.
I'm fairly new to PHP. I'm trying to filter out an array of items that contain a specific string. In order to then push those items to array, I need to pass the array to the function as a reference (or so my research has told me) however I can't seem to get it to work, any ideas? Thanks all.
$filteredS3Results = array();
function filterResults($var, &$filteredS3Results) {
if (strpos($var, '008-20160916') !== false) {
array_push($filteredS3Results, $var);
};
};
array_filter($s3Results,"filterResults");
The callback function just receives one argument, the array element being tested. It should return a boolean value that indicates whether the element should be included in the filtered result.
$filteredS3Results = array_filter($s3Results, "filterResults");
function filterResults($var) {
return strpos($var, '008-21060916') !== false;
}

Is there a better way of determining empty associative arrays in php 5.3?

The empty() function in php 5.3 does not work well for associative arrays. I have an associative array that could have some 30+ elements.
$arr = array(
'one'=>kwara,
'two'=>osun,
...
'thirty'=>lagos
)
If the associative array is empty like so:
$arr = array(
'one'=>'',
'two'=>'',
...
'thirty'=>''
)
and I need to check if the array is empty, the following will not work in php 5.3.
if(empty($arr))
{
echo "array is empty<br />>";
}
else
{
echo "array is NOT empty<br />";
}
and will return 'array is NOT empty'. I am aware that the behaviour is different in php 5.4 but my current platform is php 5.3.
To overcome this problem, I have used the following:
if(strlen(implode('',array_values($arr))) > 0)
{
echo "array is NOT empty<br />>";
}
else
{
echo "array is empty<br />";
}
The question is: is there a better of achieving this in php 5.3?
Short answer: No
Longer answer: The array you are looking at is not empty at all, it contains a bunch of keys with zero length strings. Your solution is probably one of the shortest possible and readable. You may want to wrap it in a function of your own though.
Have you tried:
if (sizeof(array_filter($array)) === 0) // do your stuff
Also you original could be improved like:
if (implode($array) !== '') // do your stuff
Empty will work only with really empty values, your array has keys assigned so its not empty. Your solution is probably best way to do what you want - its hard to say, you would need to make some benchmarks, it can be done in many other ways:
if (array_filter($arr) === array()) {}
// or
if (!implode('', $arr)) {}

Recursive function: echo works, return doesn't [duplicate]

This question already has answers here:
How to use return inside a recursive function in PHP
(4 answers)
Closed 9 months ago.
The function aims at finding an item in a range of arrays, and then returning its key.
Problem is that the function doesn't return anything, whereas it would echo the expected result...
Here is my code:
function listArray($tb, $target){
foreach($tb as $key => $value){
if(is_array($value)){ // current value is an array to explore
$_SESSION['group'] = $key; // saving the key in case this array contains the searched item
listArray($value, $target);
}else {
if ($target == $value) { // current value is the matching item
return $_SESSION['group']; //Trying to return its key
break; // I'd like to close foreach as I don't need it anymore
}
}
}
}
By the way, an other little thing: I'm not used to recursive function, and I didn't find any other solution than using a session variable. But there might be a nicer way of doing it, as I don't use this session variable elsewhere...
You need a return before the recurring listArray call.
Thank about it ..
return;
break;
That break is never reached (I don't believe you can use break to exit a function in php anyway)
The second return returns from a recursive call. Let's say that this was not two separate functions:
function foon() {
barn();
}
function barn() {
return true;
}
foon has no return statement.
I finally bypassed the problem by storing my result in a $_SESSION variable.
So, no return anymore...
$_SESSION['item'][$target] = $_SESSION['group'];

How to filter array values from another arrays values and return new array? [duplicate]

This question already has answers here:
Remove item from array if it exists in a 'disallowed words' array
(2 answers)
Closed 4 months ago.
I have two arrays: $all_languages and $taken_languages. One contains all languages (like 200 or something), but second - languages that have been chosen before (from 0 to 200).
I need to remove all languages that have been taken ($taken_languages) from $all_languages and return new array - $available_languages.
My solution was two loops, but, first, it doesn't work as expected, second - it's 'not cool' and I believe that there are better solutions! Can you point me to the correct path?
This is what I have done before, but, as I said, it doesn't work as expected...
if (!empty($taken_languages)) {
foreach ($all_languages as $language) {
foreach ($taken_languages as $taken_language) {
if ($taken_language != $language) {
$available_languages[] = $language;
break;
}
}
}
} else {
$available_languages = $all_languages;
}
Thanks in advice!
PHP has a built in function for this (and just about everything else :P)
$available_languages = array_diff($all_languages, $taken_languages);
PHP Manual (array_diff)
The array_diff function will work for you.
http://php.net/manual/en/function.array-diff.php

what is the fastest method to check if given array has array or non-array or both values?

We gave a given array which can be in 4 states.
array has values that are:
only arrays
only non-arrays
both array and non array
array has no values
Considering than an array-key can only be a numerical or string value (and not an array), I suppose you want to know about array-values ?
If so, you'll have to loop over your array, testing, for each element, if it's an array or not, keeping track of what's been found -- see the is_array function, about that.
Then, when you've tested all elements, you'll have to test if you found arrays, and/or non-array.
Something like this, I suppose, might do the trick :
$has_array = false;
$has_non_array = false;
foreach ($your_array as $element) {
if (is_array($element)) {
$has_array = true;
} else {
$has_non_array = true;
}
}
if ($has_array && $has_non_array) {
// both
} else {
if ($has_array) {
// only arrays
} else {
// only non-array
}
}
(Not tested, but the idea should be there)
This portion of code should work for the three first points you asked for.
To test for "array has no value", The fastest way is to use the empty() language construct before the loop -- and only do the loop if the array is not empty, to avoid any error.
You could also count the number of elements in the array, using the count() function, and test if it's equal to 0, BTW.
Some precalculation:
function isArray($reducedValue, $currentValue) {
// boolean value is converted to 0 or 1
return $reducedValue + is_array($currentValue);
}
$number_of_arrays = array_reduce($array, 'isArray', 0);
Then the different states can be evaluated as follows:
only arrays
count($array) == $number_of_arrays
only non-arrays
$number_of_arrays == 0
both array and non array keys
count($array) != $number_of_arrays
array has no keys
empty($array);
So you just need to write a function that returns the appropriate state.
Reference: in_array, array_reduce, empty

Categories