I'm new.
I have a situation where I need to loop through an array, determine if a $key in that array has a value of 1, then set a variable with the $value from different $key in the same array.
Here's what I mean.
I retrieve a JSON array from an API that looks, in part, like this:
(
[6] => Array
(
[element] => 191
[position] => 7
[multiplier] => 2
[is_captain] => 1
[is_vice_captain] =>
)
[7] => Array
(
[element] => 171
[position] => 8
[multiplier] => 1
[is_captain] =>
[is_vice_captain] =>
)
What I want to do is loop through the array, determine whether the key [is_captain] has a value (1), and set a variable using the value from a different $key, specifically [element].
For example, in the code above at [6], I want to create a variable with the value of [element] => 191 (191) if the value of [is_captain] is 1.
Here's where I left things:
for($i = 0; $i < count($players['picks']); $i++){
foreach ($fpl_team_picks['picks'][$keys[$i]] as $key => $value){
if (isset($key['is_captain'])){
$variable = $value['element'];
}
}
}
It doesn't work. I've tried the isset function and a series of array functions (array_column and others), and I'm stumped.
$arr = array(
6 => array(
'element' => 191,
'position' => 7,
'multiplier' => 2,
'is_captain' => 1,
'is_vice_captain' => null
),
7 => array(
'element' => 171,
'position' => 8,
'multiplier' => 1,
'is_captain' => null,
'is_vice_captain' => null
)
);
Set foreach loop on the array, set the values, loop through values, find the key value, $index === 'is_captain' and make sure it is set to 1 -> $data === '1'. If this is true define your variable.
foreach($arr as $value){
foreach($value as $index => $data){
if($index === 'is_captain' && $data === 1){
$element = $value['element'];
echo $element; // $element now holds the value where key = `element` if 'is_captain' is equal to `1`
}
}
}
In your code, change the $key['is_captain'] to $key === 'is_captain' then look for its value if it is a match with in that same conditional.
If the key is equal to target key is_captain and that keys value is equal to 1 get the value of the key set as element and assign it to your variable:
if ($key === 'is_captain' && $val === 1)){
$variable = $value['element'];
}
I was set in the right direction, so thanks immensely to the contributor for the help.
My original question didn't make clear that I was working with a nested array. My array snippet didn't show that. I've learned a lesson about completeness. (I'm new here).
Once I wrote the code block to handle the nested array and modified the conditional slightly, I was successful. Here's the final code which works:
$x = 0;
$captainsArr = array($fpl_team_picks['picks']);
foreach($captainsArr[$x++] as $value) {
if (is_array($value)){
foreach ($value as $index => $data) {
if ($index === 'is_captain' && $data == 1){
$captain = $value['element'];
}
}
}
}
I have a script where I want to get name of a column in array().
From API, I can get an array() with multiple values and I would like to get the name of a specific column.
I don't have columns' names, how do I get a list of them and fetch one by one?
Here, I want to get "573" only.
Array ( [success] => 1 [errors] => Array ( ) [data] => Array ( [Messages] => Array ( [573] => PHP is fun ) ) )
Thanks.
You just have to do a recursive iterator that will use itself to recurse or return a value based on the key match:
<?php
$arr = array(
'success' => 1,
'errors' => array(),
'data' => array(
'Messages' => array(
573 => 'PHP is fun'
)
)
);
function recurseIt($array,$find = false)
{
# Loop through array
foreach($array as $key => $value) {
# If the key is the same as the value
if($key == $find)
# Send back the value
return $value;
# If the value is an array
if(is_array($value)) {
# Use same array to recurse the array
$val = recurseIt($value,$find);
# If there is a value to return
if(!empty($val))
# Send it back
return $val;
}
}
}
# Note, if the key matches, could also be an array
echo recurseIt($arr,573);
Gives you:
PHP is fun
EDIT:
Presumably you have the value if you don't know the key, so this will return the key based on the search value:
function recurseIt($array,$find = false)
{
foreach($array as $key => $value) {
# If the key is the same as the value
if(!is_array($value) && ($value == $find))
# Send back the key name
return $key;
if(is_array($value)) {
$val = recurseIt($value,$find);
if(!empty($val))
return $val;
}
}
}
echo recurseIt($arr,'PHP is fun');
Gives you:
573
Now, if you don't know what the key name is and don't know the associated value would be, then the function doesn't know how to search. read_my_mind() is not yet in the PHP library so at that point you are pretty much out of luck.
I am trying to delete an array whereby one of its values..(time) meet a specific condition. \The code I'm currently working with looks like this:
foreach($_SESSION as $key) {
foreach($key['time'] as $keys=>$value){
if(condition){
unset($key);
}
}
}
The array looks like this.
Array
(
[form1] => Array
(
[hash] => lFfKBKiCTG6vOQDa8c7n
[time] => 1401067044
)
[form5] => Array
(
[hash] => TTmLVODDEkI1NrRnAbfB
[time] => 1401063352
)
[form4] => Array
(
[hash] => XCVOvrGbhuqAZehBmwoD
[time] => 1401063352
)
I tried to adapt solutions from these pages but didn't work.
Remove element in multidimensional array and save
PHP - unset in a multidimensional array
PHP How to Unset Member of Multidimensional Array?
If you want to unset the values inside it, a simple single foreach will suffice. Consider this example:
$values = array(
'form1' => array('hash' => 'lFfKBKiCTG6vOQDa8c7n', 'time' => 1401067044),
'form5' => array('hash' => 'TTmLVODDEkI1NrRnAbfB', 'time' => 1401063352),
'form4' => array('hash' => 'XCVOvrGbhuqAZehBmwoD', 'time' => 1401063352),
);
$needle = 1401067044;
foreach($values as $key => &$value) {
if($value['time'] == $needle) {
// if you want to remove this key pair use this
unset($values[$key]['time']);
// if you just want to remove the value inside it
$value['time'] = null;
// if you want to remove all of this entirely
unset($values[$key]);
}
}
Fiddle
Unsetting in a for loop can lead to issues, its easier and better to use array_filter which is optimized for this kind of problem. Here is how to do it with your example. ideone running code
<?php
$ar = Array(
"form1" => Array
(
"hash" => 'lFfKBKiCTG6vOQDa8c7n',
"time" => '1401067044'
),
"form5" => Array
(
"hash" => 'TTmLVODDEkI1NrRnAbfB',
"time" => '1401063352'
),
"form4" => Array
(
"hash" => 'XCVOvrGbhuqAZehBmwoD',
"time" => '1401063352'
)
);
$condition = '1401067044';
$newArray = array_filter($ar, function($form) use ($condition) {
if (!isset($form['time'])) {
return true;
}
return $form['time'] != $condition;
});
var_export($newArray);
array_filter
Assuming your values are stored in $_SESSION
foreach($_SESSION as $key => $value) {
if(isset($value['time']) && $value['time'] < 1401063352) {
unset($_SESSION[$key]);
}
}
If you are storing your values in $_SESSION you may want to consider storing them in a subfield like $_SESSION['myForms'] so if you need to add other values to your session you can easily access only the values you need.
You need to do
unset($_SESSION[$key])
However as mentioned by Victory, array_filter is probably a better approach to this.
I am trying to unset a group of array keys that have the same prefix. I can't seem to get this to work.
foreach ($array as $key => $value) {
unset($array['prefix_' . $key]);
}
How can I get unset to see ['prefix_' . $key] as the actual variable? Thanks
UPDATE: The $array keys will have two keys with the same name. Just one will have the prefix and there are about 5 keys with prefixed keys:
Array {
[name] => name
[prefix_name] => other name
}
I don't want to remove [name] just [prefix_name] from the array.
This works:
$array = array(
'aa' => 'other value aa',
'prefix_aa' => 'value aa',
'bb' => 'other value bb',
'prefix_bb' => 'value bb'
);
$prefix = 'prefix_';
foreach ($array as $key => $value) {
if (substr($key, 0, strlen($prefix)) == $prefix) {
unset($array[$key]);
}
}
If you copy/paste this code at a site like http://writecodeonline.com/php/, you can see for yourself that it works.
You can't use a foreach because it's only a copy of the collection. You'd need to use a for or grab the keys separately and separate your processing from the array you want to manipulate. Something like:
foreach (array_keys($array) as $keyName){
if (strncmp($keyName,'prefix_',7) === 0){
unset($array[$keyName]);
}
}
You're also already iterating over the collection getting every key. Unless you had:
$array = array(
'foo' => 1,
'prefix_foo' => 1
);
(Where every key also has a matching key with "prefix_" in front of it) you'll run in to trouble.
I'm not sure I understand your question, but if you are trying to unset all the keys with a specific prefix, you can iterate through the array and just unset the ones that match the prefix.
Something like:
<?php
foreach ($array as $key => $value) { // loop through keys
if (preg_match('/^prefix_/', $key)) { // if the key stars with 'prefix_'
unset($array[$key]); // unset it
}
}
You're looping over the array keys already, so if you've got
$array = (
'prefix_a' => 'b',
'prefix_c' => 'd'
etc...
)
Then $keys will be prefix_a, prefix_c, etc... What you're doing is generating an entirely NEW key, which'd be prefix_prefix_a, prefix_prefix_c, etc...
Unless you're doing something more complicated, you could just replace the whole loop with
$array = array();
I believe this should work:
foreach ($array as $key => $value) {
unset($array['prefix_' . str_replace('prefix_', '', $key]);
}
I need to search a multidimensional array for a specific value in any of the indexed subarrays.
In other words, I need to check a single column of the multidimensional array for a value. If the value exists anywhere in the multidimensional array, I would like to return true otherwise false
$my_array = array(
0 => array(
"name" => "john",
"id" => 4
),
1 => array(
"name" => "mark",
"id" => 152
),
2 => array(
"name" => "Eduard",
"id" => 152
)
);
I would like to know the fastest and most efficient way to check if the array $my_array contains a value with the key "id". For example, if id => 152 anywhere in the multidimensional array, I would like true.
Nothing will be faster than a simple loop. You can mix-and-match some array functions to do it, but they'll just be implemented as a loop too.
function whatever($array, $key, $val) {
foreach ($array as $item)
if (isset($item[$key]) && $item[$key] == $val)
return true;
return false;
}
The simplest way is this:
$my_array = array(
0 => array(
"name" => "john",
"id" => 4
),
1 => array(
"name" => "mark",
"id" => 152
),
2 => array(
"name" => "Eduard",
"id" => 152
)
);
if (array_search(152, array_column($my_array, 'id')) !== FALSE) {
echo 'FOUND!';
} else {
echo 'NOT FOUND!';
}
** PHP >= 5.5
simply u can use this
$key = array_search(40489, array_column($userdb, 'uid'));
Let's suppose this multi dimensional array:
$userdb=Array
(
(0) => Array
(
(uid) => '100',
(name) => 'Sandra Shush',
(url) => 'urlof100'
),
(1) => Array
(
(uid) => '5465',
(name) => 'Stefanie Mcmohn',
(pic_square) => 'urlof100'
),
(2) => Array
(
(uid) => '40489',
(name) => 'Michael',
(pic_square) => 'urlof40489'
)
);
$key = array_search(40489, array_column($userdb, 'uid'));
Here is an updated version of Dan Grossman's answer which will cater for multidimensional arrays (what I was after):
function find_key_value($array, $key, $val)
{
foreach ($array as $item)
{
if (is_array($item) && find_key_value($item, $key, $val)) return true;
if (isset($item[$key]) && $item[$key] == $val) return true;
}
return false;
}
If you have to make a lot of "id" lookups and it should be really fast you should use a second array containing all the "ids" as keys:
$lookup_array=array();
foreach($my_array as $arr){
$lookup_array[$arr['id']]=1;
}
Now you can check for an existing id very fast, for example:
echo (isset($lookup_array[152]))?'yes':'no';
A good solution can be one provided by #Elias Van Ootegan in a comment that is:
$ids = array_column($array, 'id', 'id');
echo isset($ids[40489])?"Exist":"Not Exist";
I tried it and worked for me, thanks buddy.
Edited
Note: It will work in PHP 5.5+
TMTOWTDI. Here are several solutions in order of complexity.
(Short primer on complexity follows):O(n) or "big o" means worst case scenario where n means the number of elements in the array, and o(n) or "little o" means best case scenario. Long discrete math story short, you only really have to worry about the worst case scenario, and make sure it's not n ^ 2 or n!. It's more a measure of change in computing time as n increases than it is overall computing time. Wikipedia has a good article about computational aka time complexity.
If experience has taught me anything, it's that spending too much time optimizing your programs' little-o is a distinct waste of time better spent doing something - anything - better.
Solution 0: O(n) / o(1) complexity:
This solution has a best case scenario of 1 comparison - 1 iteration thru the loop, but only provided the matching value is in position 0 of the array. The worst case scenario is it's not in the array, and thus has to iterate over every element of the array.
foreach ($my_array as $sub_array) {
if (#$sub_array['id'] === 152) {
return true;
}
}
return false;
Solution 1: O(n) / o(n) complexity:
This solution must loop thru the entire array no matter where the matching value is, so it's always going to be n iterations thru the array.
return 0 < count(
array_filter(
$my_array,
function ($a) {
return array_key_exists('id', $a) && $a['id'] == 152;
}
)
);
Solution 2: O(n log n) / o(n log n) complexity:
A hash insertion is where the log n comes from; n hash insertions = n * log n. There's a hash lookup at the end which is another log n but it's not included because that's just how discrete math works.
$existence_hash = [];
foreach ($my_array as $sub_array) {
$existence_hash[$sub_array['id']] = true;
}
return #$existence_hash['152'];
I came upon this post looking to do the same and came up with my own solution I wanted to offer for future visitors of this page (and to see if doing this way presents any problems I had not forseen).
If you want to get a simple true or false output and want to do this with one line of code without a function or a loop you could serialize the array and then use stripos to search for the value:
stripos(serialize($my_array),$needle)
It seems to work for me.
As in your question, which is actually a simple 2-D array wouldn't it be better? Have a look-
Let say your 2-D array name $my_array and value to find is $id
function idExists($needle='', $haystack=array()){
//now go through each internal array
foreach ($haystack as $item) {
if ($item['id']===$needle) {
return true;
}
}
return false;
}
and to call it:
idExists($id, $my_array);
As you can see, it actually only check if any internal index with key_name 'id' only, have your $value. Some other answers here might also result true if key_name 'name' also has $value
I don't know if this is better or worse for performance, but here is an alternative:
$keys = array_map(function($element){return $element['id'];}, $my_array);
$flipped_keys = array_flip($keys);
if(isset($flipped_keys[40489]))
{
// true
}
You can create a queue of sub-arrays and loop each:
function existsKeyValue($myArray, $key, $value) {
$queue = [$myArray]; //creating a queue of a single element, which is our outermost array
//when we reach the count of the queue we looped all inner loops as well and failed to find the item
for ($index = 0; $index < count($queue); $index++) {
//Looping the current array, finding the key and the value
foreach ($queue[$index] as $k => &$v) {
//If they match the search, then we can return true
if (($key === $k) && ($value === $v)) {
return true;
}
//We need to make sure we did not already loop our current array to avoid infinite cycles
if (is_array($v)) $queue[]=$v;
}
}
return false;
}
$my_array = array(
0 => array(
"name" => "john",
"id" => 4
),
1 => array(
"name" => "mark",
"id" => 152
),
2 => array(
"name" => "Eduard",
"id" => 152
)
);
echo var_dump(existsKeyValue($my_array, 'id', 152));
array_column returns the values of a single column of an array and we can search for a specific value for those via in_array
if (in_array(152, array_column($my_array, 'id'))) {
echo 'FOUND!';
} else {
echo 'NOT FOUND!';
}
Try with this below code. It should be working fine for any kind of multidimensional array search.
Here you can see LIVE DEMO EXAMPLE
function multi_array_search($search_for, $search_in) {
foreach ($search_in as $element) {
if ( ($element === $search_for) ){
return true;
}elseif(is_array($element)){
$result = multi_array_search($search_for, $element);
if($result == true)
return true;
}
}
return false;
}
You can use this with only two parameter
function whatever($array, $val) {
foreach ($array as $item)
if (isset($item) && in_array($val,$item))
return 1;
return 0;
}
different between isset vs array_key_exits
What's the difference between isset() and array_key_exists()?
different between == vs === How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?
function specificValue(array $array,$key,$val) {
foreach ($array as $item)
if (array_key_exits($item[$key]) && $item[$key] === $val)
return true;
return false;
}
function checkMultiArrayValue($array) {
global $test;
foreach ($array as $key => $item) {
if(!empty($item) && is_array($item)) {
checkMultiArrayValue($item);
}else {
if($item)
$test[$key] = $item;
}
}
return $test;
}
$multiArray = array(
0 => array(
"country" => "",
"price" => 4,
"discount-price" => 0,
),);
$test = checkMultiArrayValue($multiArray);
echo "<pre>"
print_r($test);
Will return array who have index and value
I wrote the following function in order to determine if an multidimensional array partially contains a certain value.
function findKeyValue ($array, $needle, $value, $found = false){
foreach ($array as $key => $item){
// Navigate through the array completely.
if (is_array($item)){
$found = $this->findKeyValue($item, $needle, $value, $found);
}
// If the item is a node, verify if the value of the node contains
// the given search parameter. E.G.: 'value' <=> 'This contains the value'
if ( ! empty($key) && $key == $needle && strpos($item, $value) !== false){
return true;
}
}
return $found;
}
Call the function like this:
$this->findKeyValue($array, $key, $value);