How do I know if a key in an array is true? If not, then don't use this
[0] => array
(
[id] => 1
[some_key] => something
)
[1] => array
(
[id] => 2
)
[2] => array
(
[id] => 3
[some_key] => something
)
foreach($array as $value){
$id = $value->id;
if($value->some_key === TRUE){
$some_key = $value->some_key; //some may have this key, some may not
}
}
Not sure what is the proper statement to check if this array has that some_key. If I don't have a check, it will output an error message.
Thanks in advance.
Try
isset($array[$some_key])
It will return true if the array $array has an index $some_key, which can be a string or an integer.
Others have mentioned isset(), which mostly works. It will fail if the value under the key is null, however:
$test = array('sampleKey' => null);
isset($test['sampleKey']); // returns false
If this case is important for you to test, there's an explicit array_key_exists() function which handles it correctly:
http://php.net/manual/en/function.array-key-exists.php
You can use the isset() function to see if a variable is set.
foreach($array as $value){
$id = $value->id;
if(isset($value->some_key)){
$some_key = $value->some_key;
}
}
function validate($array)
{
foreach($array as $val) {
if( !array_key_exists('id', $val) ) return false;
if( !array_key_exists('some_key', $val) ) return false;
}
return true;
}
Related
I have array like below.
(
[TestData1] => Array
(
[0] => Array
(
[SKU] => A01
[SKUType] => Test
[State] => Yes
)
[1] => Array
(
[SKU] => A02
[SKUType] => Test
[State] => Yes
)
[2] => Array
(
[SKU] => A01
[SKUType] => Test
[State] => Yes
)
[3] => Array
(
[SKU] => A03
[SKUType] => Test
[State] => Yes
)
)
[TestData2] => Array
(
)
[TestData3] => Array
(
)
)
I need to check if the given SKU is exist or not in the TestData1 array.
If exist need to check the State value that should be Yes.
Example given sku is
$skutotest = 'A01';
How to find if the value present in the above array using PHP.
Right now i tried like below.
$Details = result_array; // here reading array data from api
$parent_sku = A01;
$Results = $Details['$TestData1'];
foreach($Results as $res){
$sku= $res['SKU'];
$state = $res['State'];
if($sku== $parent_sku && $state == "Yes"){
return true;
break;
}else{
return false;
}
}
Once i found the match, need to stop executing and return true, is the above code correct?
Can anyone help me with this. Thanks
Check this one liner,
$exists = false;
$key = "TestData1";
$skutotest = "A01";
if (array_key_exists($key, $arr)) { // for check if key exists
return ($arr[$key][array_search($skutotest, array_column($arr[$key], 'SKU'))]['State'] == 'Yes');
}
array_search — Searches the array for a given value and returns the first corresponding key if successful
array_column — Return the values from a single column in the input array
Demo.
EDIT
Proper solution for your problem,
$exists = false;
$key = "TestData1";
$val = "A01";
if (array_key_exists($key, $arr)) {
array_walk($arr[$key], function ($item) use ($val, &$exists) {
if ($item['SKU'] == $val && $item['State'] == 'Yes') {
$exists = true;
return;
}
});
}
return ($exists);
Demo
Following function has been used in the solution :
array_combine() - Creates an array by using one array for keys and another for its values
array_column() - Return the values from a single column in the input array
array_key_exists() - Checks if the given key or index exists in the array
$skuToSearch = 'A01';
$parentKey = 'TestData1';
$res = array_combine(
array_column($arr[$parentKey] , 'SKU'),
array_column($arr[$parentKey] , 'State')
);
$found = (array_key_exists($skuToSearch, $res) && $res[$skuToSearch] == 'Yes') ? true : false;
Explanation:
variable $skuToSearch, put the SKU which you want to search.
variable $parentKey hold the key of the parent subarray.
array_column($arr[$parentKey] , 'SKU') will return an array with SKU's
array_column($arr[$parentKey] , 'State') will return an array with States
Variable $found will return true OR false, if the SKU found and have state values Yes
I have the following array:
Array
(
[0] => Array
(
[CODE] => OK
[company_id] => 170647449000
[taxnumber] => 944703420
[name] => SOME NAME
[title] => S.A
)
[1] => Array
(
[CODE] => OK
[company_id] => 17063649000
[taxnumber] => 999033420
[name] => SOME OTHER NAME
[title] => ANOTHER DIFFERENT TITLE
)
)
If the array contain the company_id with the value 17063649000 I need to extract that array (1) in an new array, so I can manipulate it further.
I make numerous code snippets but I am not even close to the solution. I still can not figure out how can I find if the $value (17063649000) exists in the array....not to mention how to extract that specific array (1) from the existing array....
My latest attempt was to modify this and to make it to work, but I am still not managing to make it:
function myfunction($agents, $field, $value)
{
foreach($agents as $key => $agent)
{
if ( $agent[$field] === $value )
return $key;
}
return false;
}
I always get false, even I am sending the value that exists.
Replace return $key with return $agent and operator === with ==.
=== checks type too, it could be reason why it doesn't work.
if your array is $companies then
function getCompany($search_id, $companies) {
foreach($company in $companies) {
if ($companies['company_id'] == $search_id) {
return $company;
}
}
return false;
}
$companies = [...];
$search = 17063649000;
if ($company = getCompany($search, $companies) ) {
// do something with $company
} else {
// not found
}
Hi I have an object array ($perms_found) as follow:
Array
(
[0] => stdClass Object
(
[permissions_id] => 1
)
[1] => stdClass Object
(
[permissions_id] => 2
)
[2] => stdClass Object
(
[permissions_id] => 3
)
)
I want to use in_array to find any of the permissions_id , I have tried this:
var_dump(in_array(1, $perms_found , true));
But I keep getting :
bool(false)
What I am doing wrong please help?
in_array is looking for 1 in the array, but your array contains objects, not numbers. Use a loop that accesses the object properties:
$found = false;
foreach ($perms_found as $perm) {
if ($perm->permissions_id == 1) {
$found = true;
break;
}
}
Firstly convert to array...
function objectToArray($object) {
if (!is_object($object) && !is_array($object)) {
return $object;
}
if (is_object($object)) {
$object = get_object_vars($object);
}
return array_map('objectToArray', $object);
}
in_array() will check if the element, in this case 1, exists in the given array.
Aparently you have an array like this:
$perms_found = array(
(object)array('permissions_id' => 1),
(object)array('permissions_id' => 2),
(object)array('permissions_id' => 3)
);
So you have an array with 3 elements, none of them is the numeric 1, they are all objects. You cannot use in_array() in this situation.
If you want to check for the permission_id on those objects, you will have to wrote your own routine.
function is_permission_id_in_set($perm_set, $perm_id)
{
foreach ($perm_set as $perm_obj)
if ($perm_obj->permission_id == $perm_id)
return true;
return false;
}
var_dump(is_permission_id_in_set($perms_found, 1));
Your array is collection of objects and you're checking if an integer is in that array. You should first use array_map function.
$mapped_array = array_map($perms_found, function($item) { return $item->permissions_id });
if (in_array($perm_to_find, $mapped_array)) {
// do something
}
This question already has answers here:
How to Flatten a Multidimensional Array?
(31 answers)
Closed 5 months ago.
Is there any fast way to flatten an array and select subkeys ('key'&'value' in this case) without running a foreach loop, or is the foreach always the fastest way?
Array
(
[0] => Array
(
[key] => string
[value] => a simple string
[cas] => 0
)
[1] => Array
(
[key] => int
[value] => 99
[cas] => 0
)
[2] => Array
(
[key] => array
[value] => Array
(
[0] => 11
[1] => 12
)
[cas] => 0
)
)
To:
Array
(
[int] => 99
[string] => a simple string
[array] => Array
(
[0] => 11
[1] => 12
)
)
Give this a shot:
$ret = array();
while ($el = each($array)) {
$ret[$el['value']['key']] = $el['value']['value'];
}
call_user_func_array("array_merge", $subarrays) can be used to "flatten" nested arrays.
What you want is something entirely different. You could use array_walk() with a callback instead to extract the data into the desired format. But no, the foreach loop is still faster. There's no array_* method to achieve your structure otherwise.
Hopefully it will help someone else, but here is a function I use to flatten arrays and make nested elements more accessible.
Usage and description here:
https://totaldev.com/flatten-multidimensional-arrays-php/
The function:
// Flatten an array of data with full-path string keys
function flat($array, $separator = '|', $prefix = '', $flattenNumericKeys = false) {
$result = [];
foreach($array as $key => $value) {
$new_key = $prefix . (empty($prefix) ? '' : $separator) . $key;
// Make sure value isn't empty
if(is_array($value)) {
if(empty($value)) $value = null;
else if(count($value) == 1 && isset($value[0]) && is_string($value[0]) && empty(trim($value[0]))) $value = null;
}
$hasStringKeys = is_array($value) && count(array_filter(array_keys($value), 'is_string')) > 0;
if(is_array($value) && ($hasStringKeys || $flattenNumericKeys)) $result = array_merge($result, flat($value, $separator, $new_key, $flattenNumericKeys));
else $result[$new_key] = $value;
}
return $result;
}
This should properly combine arrays with integer keys. If the keys are contiguous and start at zero, they will be dropped. If an integer key doesn't yet exist in the flat array, it will be kept as-is; this should mostly preserve non-contiguous arrays.
function array_flatten(/* ... */)
{
$flat = array();
array_walk_recursive(func_get_args(), function($value, $key)
{
if (array_key_exists($key, $flat))
{
if (is_int($key))
{
$flat[] = $value;
}
}
else
{
$flat[$key] = $value;
}
});
return $flat;
}
You could use !isset($key) or empty($key) instead to favor useful values.
Here's a more concise version:
function array_flatten(/* ... */)
{
$flat = array();
array_walk_recursive(func_get_args(), function($value, $key) use (&$flat)
{
$flat = array_merge($flat, array($key => $value));
});
return $flat;
}
I have an array that looks like this:
Array
(
[0] => Array
(
[0] => 1
[id] => 1
)
[1] => Array
(
[0] => 2
[id] => 2
)
)
What I would like to do is compare an int value against what's in the id value field. So, if I were to pass in say a 1, I'd like to be able to have a function compare this. I was thinking in_array but I can't get that to work. Does anyone know what function I can use for this?
Thanks.
It's not entirely clear what you'd like the result of the function to be, however I'm guessing you'd like the key of array that contains the ID you are looking for, in that case the following function would find that.
<?php
function get_key($array, $id) {
foreach ($array as $key => $unit) {
if ($unit['id'] == $id) {
return $key;
}
}
}
Try something like this:
$needle = 1;
$found = false;
foreach ($array as $key => $val) {
if ($val['id'] === 1) {
$found = $key;
break;
}
}
if ($found !== false) {
echo 'found in $array['.$found.']';
}
Since you want something more compact:
$needle = 1;
array_filter($array, create_function('$val', 'return $val["id"] !== '.var_export($needle, true).';'))
That will filter out all those elements that’s id value is not 1.