I have a simple array of boolean arrays as follows:
array(
array('dog' => true),
array('cat' => true),
array('bird' =>false),
array('fish' => true)
)
How can I find an entry, such as 'cat', without a loop construct? I think I should be able to accomplish this with a php array function, but the solution is eluding me! I just want to know if 'cat' is a valid key - I'm not interested in it's value.
In the example above, 'cat' should return true, while 'turtle' should return false.
$array = array(
array('dog' => true),
array('cat' => true),
array('bird' =>false),
array('fish' => true)
);
array_walk($array,'test_array');
function test_array($item2, $key){
$isarray = is_array($item2) ? 'Is Array<br>' : 'No array<br>';
echo $isarray;
}
using array_walk example in the manual
Output:
Is Array
Is Array
Is Array
Is Array
Ideone
You could achieve it like this :
Reduce your array to a single dimensional array using combination of array_reduce and array_merge PHP functions .
In the reduced array , look for the key using array_key_exists .
Your array :
$yourArray = array
(
array( 'dog' => true )
,array( 'cat' => true )
,array( 'bird' =>false )
,array( 'fish' => true )
);
Code to check if a key exists :
$itemToFind = 'cat'; // turtle
$result =
array_key_exists
(
$itemToFind
,array_reduce(
$yourArray
,function ( $v , $w ){ return array_merge( $v ,$w ); }
,array()
)
);
var_dump( $result );
Code to check if a key exits and to retrieve its value :
$itemToFind = 'cat'; // bird
$result =
array_key_exists
(
$itemToFind
,$reducedArray = array_reduce(
$yourArray
,function ( $v , $w ){ return array_merge( $v ,$w ); }
,array()
)
) ?$reducedArray[ $itemToFind ] :null;
var_dump( $result );
Using PHP > 5.5.0
You could use combination of array_column and count PHP functions to achieve it :
Code to check if a key exists :
$itemToFind = 'cat'; // turtle
$result = ( count ( array_column( $yourArray ,'cat' ) ) > 0 ) ? true : false;
var_dump( $result );
The above code tested with PHP 5.5.5 is here
Related
I have an array with the following setup:
array(
array(
'product_id' => 733
),
array(
'product_name' => Example
)
)
I want to check that 733 exists in my array which I need to use array_search (going by googling) as in_array doesn't work on m-d arrays.
My code is:
$key = array_search( '733', array_column( $items, 'product_id' ) );
If I var_dump the $items array I can see the product_id
I want to check the specific ID exists in the array and then perform other code.
So basically you want to check that given product-id exist in your multidimensional array or not?
You can do it like below:-
<?php
$items = array(
array(
'product_id' => 733
),
array(
'product_name' => Example
)
);
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if (!empty($val['product_id']) && $val['product_id'] == $id) {
return "true"; // or return key according to your wish
}
}
return "false";
}
echo $found = searchForId(733, $items);
Output:- https://eval.in/805075
Reference taken:- https://stackoverflow.com/a/6661561/4248328
I have a loop that builds an array of associative arrays that looks like this:
array(
'foo' => '',
'bar' => '',
'thingys' => array()
)
on each iteration of the loop, I want to search through the array for an associate array that's 'foo' and 'bar' properties match those of the current associate array. If it exists I want to append the thingys property of the current associative array to the match. Otherwise append the entire thing.
I know how to do this with for loops, but I'm wondering if there is a simpler way to do this with an array function. I'm on php 5.3.
Example
<?php
$arr = array(
array(
'foo' => 1,
'bar' => 2,
'thing' => 'apple'
),
array(
'foo' => 1,
'bar' => 2,
'thing' => 'orange'
),
array(
'foo' => 2,
'bar' => 2,
'thing' => 'apple'
),
);
$newArr = array();
for ($i=0; $i < count($arr); $i++) {
$matchFound = false;
for ($j=0; $j < count($newArr); $j++) {
if ($arr[$i]['foo'] === $newArr[$j]['foo'] && $arr[$i]['bar'] === $newArr[$j]['bar']) {
array_push($newArr[$j]['thing'], $arr[$i]['things']);
$matchFound = true;
break;
}
}
if (!$matchFound) {
array_push($newArr,
array(
'foo' => $arr[$i]['foo'],
'bar' => $arr[$i]['bar'],
'things' => array($arr[$i]['thing'])
)
);
}
}
/*Output
$newArr = array(
array(
'foo' => 1,
'bar' => 2,
'things' => array('orange', 'apple')
),
array(
'foo' => 2,
'bar' => 2,
'things' => array('apple')
),
)
*/
?>
I don't know if it is possible through a built-in function, but I think no. Something can be implemented through array_map, but anyway you have to perform a double loop.
I propose you a one-loop solution using a temporary array ($keys) as index of already created $newArr items, based on foo and bar; elements of original array are processed through a foreach loop, and if a $keys element with first key as foo value and second key as bar value exists, then the current thing value is added to the returned key index of $newArr, otherwise a new $newArray element is created.
$newArr = $keys = array();
foreach( $arr as $row )
{
if( isset( $keys[$row['foo']][$row['bar']] ) )
{ $newArr[$keys[$row['foo']][$row['bar']]]['thing'][] = $row['thing']; }
else
{
$keys[$row['foo']][$row['bar']] = array_push( $newArr, $row )-1;
$newArr[$keys[$row['foo']][$row['bar']]]['thing'] = array( $row['thing'] );
}
}
unset( $keys );
3v4l.org demo
Edit: array_map variant
This is the same solution above, using array_map instead of foreach loop. Note that also your original code can be converted in this way.
$newArr = $keys = array();
function filterArr( $row )
{
global $newArr, $keys;
if( isset( $keys[$row['foo']][$row['bar']] ) )
{ $newArr[$keys[$row['foo']][$row['bar']]]['thing'][] = $row['thing']; }
else
{
$keys[$row['foo']][$row['bar']] = array_push( $newArr, $row )-1;
$newArr[$keys[$row['foo']][$row['bar']]]['thing'] = array( $row['thing'] );
}
}
array_map( 'filterArr', $arr );
3v4l.org demo
I would like to build a multidimensional array from an array. For example I would like
$test = array (
0 => 'Tree',
1 => 'Trunk',
2 => 'Branch',
3 => 'Limb',
4 => 'Apple',
5 => 'Seed'
);
to become
$test =
array (
'Tree' => array (
'Trunk' => array (
'Branch' => array (
'Limb' => array (
'Apple' => array (
'Seed' => array ()
)
)
)
)
)
);
or more simply
$result[Tree][Trunk][Branch][Limb][Apple][Seed] = null;
I'm trying to do this with a recursive function but i'm hitting memory limit so I'm clearly doing it wrong.
<?php
$test = array (
0 => 'Tree',
1 => 'Trunk',
2 => 'Branch',
3 => 'Limb',
4 => 'Apple',
5 => 'Seed'
);
print_r($test);
print "results of function";
print_r(buildArray($test));
function buildArray (&$array, &$build = null)
{
if (count($array) > 0)
{
//create an array, pass the array to itself removing the first value
$temp = array_values($array);
unset ($temp[0]);
$build[$array[0]] = $temp;
buildArray($build,$temp);
return $build;
}
return $build;
}
Here's an approach with foreach and without recursion, which works:
function buildArray($array)
{
$new = array();
$current = &$new;
foreach($array as $key => $value)
{
$current[$value] = array();
$current = &$current[$value];
}
return $new;
}
[ Demo ]
Now your function... first, using $build[$array[0]] without defining it as an array first produces an E_NOTICE.
Second, your function is going into infinite recursion because you are not actually modifying $array ($temp isn't the same), so count($array) > 0 will be true for all of eternity.
And even if you were modifying $array, you couldn't use $array[0] anymore, because you unset that, and the indices don't just slide up. You would need array_shift for that.
After that, you pass $build and $temp to your function, which results in further because you now you assign $build to $temp, therefore creating another loop in your already-infinitely-recurring loop.
I was trying to fix all of the above in your code, but eventually realized that my code was now pretty much exactly the one from Pevara's answer, just with different variable names, so... that's that.
This function works recursively and does the trick:
function buildArray($from, $to = []) {
if (empty($from)) { return null; }
$to[array_shift($from)] = buildArray($from, $to);
return $to;
}
In your code I would expect you see an error. You are talking to $build in your first iteration as if it where an array, while you have defaulted it to null.
It seems to be easy
$res = array();
$i = count($test);
while ($i)
$res = array($test[--$i] => $res);
var_export($res);
return
array ( 'Tree' => array ( 'Trunk' => array ( 'Branch' => array ( 'Limb' => array ( 'Apple' => array ( 'Seed' => array ( ), ), ), ), ), ), )
Using a pointer, keep re-pointing it deeper. Your two output examples gave array() and null for the deepest value; this gives array() but if you want null, replace $p[$value] = array(); with $p[$value] = $test ? array() : null;
$test = array(
'Tree',
'Trunk',
'Branch',
'Limb',
'Apple',
'Seed'
);
$output = array();
$p = &$output;
while ($test) {
$value = array_shift($test);
$p[$value] = array();
$p = &$p[$value];
}
print_r($output);
I have the follow array:
Array
(
[0] => Array
(
[type] => foo
)
[1] => Array
(
[type] => bar
)
[2] => Array
(
[type] => bar
)
)
and need to know if exists one or more type which value is bar, without do this:
foreach ($arrayOfTypes as $type) {
if ($type['type'] == 'bar')
{
// Stuff here
}
}
(Only for learning purposes)
I'd go with array_filter();
$filteredArray = array_filter($stuff, function($item){
return $item['type'] == 'bar';
});
if( count($filteredArray) > 0 ){
echo 'There was a bar item in array.';
}else{
echo 'No luck sorry!';
}
Use in_array: http://se.php.net/manual/en/function.in-array.php
Combine it with array_map to flatten what you have. Like so:
$new_array = array_map( function( $arr ) {
return $arr['type'];
}, $array );
in_array( 'bar', $new_array );
Honestly a foreach loop or moonwave99's array-filter answer is probably going to be your best bet, but if what you're looking is the shortest code possible and creativity that will make most programmers gag, you could try serialize-ing the array and using string-searching functions:
serialize(array(
0=>array(
'type' => 'foo'
),
1=>array(
'type' => 'bar'
),
2=>array(
'type' => 'bar'
)
))
becomes
a:3:{i:0;a:1:{s:4:"type";s:3:"foo";}i:1;a:1:{s:4:"type";s:3:"bar";}i:2;a:1:{s:4:"type";s:3:"bar";}}
So you can now run a strpos() or preg_match() function to find them. So your whole function would look like:
$exists = strpos('{s:4:"type";s:3:"bar";}',serialize($arrayOfTypes)); //returns number or false
It's short, it's snappy, and get's the job done for simple string keypairs.
This is basically the same as moonwave99's solution but slightly more useful as it's in a function that you can feed a key/value pair to as well, so it can be used to search for any key/value combo:
function isKVInArray($k, $v, $array) {
$filtered = array_filter($array, function($item) use($k,$v) {
return $item[$k] == $v;
});
if(count($filtered)>=1) return true;
else return false;
}
$k = 'live';
$v = 'y';
$my_array = array(
0=>array(
'live'=>'n',
'something_else'=>'a'
),
1=>array(
'live'=>'y',
'something_else'=>'b'
),
2=>array(
'live'=>'n',
'something_else'=>'c'
)
);
if(isKVInArray($k, $v, $my_array)) echo "$k=>$v was found in the array.";
else echo 'No luck sorry!';
there's another simple way which is useful when you need to count all the different values
foreach ($arrayOfTypes as $type) $cnt[$type['type']]++;
To get the number of 'bar' (or to get the count of another value):
echo($cnt['bar']);
The following array is output from my db.
$this->db->select('code')->from('table');
$array = $this->db->get()->result_array();
//Output:
Array ( [0] => Array ( [code] => ASDF123 ) [1] => Array ( [code] => ASDF124 ) )
How can I find if a variable is contained in this array?
ie.
if(this_is_in_array($value, $array) == TRUE)...
What's the simplest way to to that with PHP?
I sincerely apologize for not wording this correctly the first time.
In case you wish to find the KEY of an array you would refer to the array_key_exists() method.
An example of this would be:
$array = array(
'key1' => 'value1',
'key2' => 'value2'
);
if ( array_key_exists( 'key2', $array ) )
return TRUE;
If you would however prefer to find the VALUE of an array, you would refer to the in_array() method. An example of this would be:
$array = array(
'key1' => 'value1',
'key2' => 'value2'
);
if ( in_array( 'value1', $array ) )
return TRUE;
Kevin:
foreach( $array as $key => $values )
{
if ( $values['code'] == 'ASD1234' )
{
// do something
}
}
make your array this:
$your_array = array('key1'=>'value1', 'key2'=>'value2');
then use this to see if the key exists in the array.
if (array_key_exists('key2', $your_array)) {
Unsure about what exactly you mean in your question, however, to answer your question title, you can use the array_key_exists() function to check if a given key or index exists within an array.
put your validation into the function
$input = 'ASDF123';
function check_input($input) {
$array = array(
0 => array('code' => 'ASDF123'),
1 => array('code' => 'ASDF124')
);
foreach ($array as $codes) {
if (in_array($input, $codes)) {
return true;
}
}
return false;
}
$needle = 'ASDF123';
$ary = Array(
Array('code' => 'ASDF123'),
Array('code' => 'ASDF124')
);
$_ = "return (\$a['code']='".addslashes($needle)."');";
if (count(array_filter($ary[0],create_function('$a',$_))) > 0)
//true
I THINK (only because you use code twice, so I assume that's not the search field--or it's a semantics issue). If it is semantics, as everyone else has already suggested, try array_key_exists.