I have to check if items with keys 2, 3, 4, 5 in the sub array with index 0 are empty or not. If empty, I need to throw an exception.
If not empty, then move to next iteration, checking items with keys 3, 4, 5, 6 in the sub array with index 1, and so on.
Items with keys 0 and 1 will always be empty so nothings need to be done with them.
So, check for items with key > 1 then 4-4 pair check if anyone is empty and then throw an exception.
here is my code
$array = array(
array('0' => '','1' => '','2' => 'Wasatch standard','3' => 'Wasatch standard','4' => '3,5,2','5' => 'English','6' => '','7' => '','8' => ''),
array('0' => '','1' => '','2' => '','3' => 'ThisIsAtest','4' => 'Wasatch standard1','5' => '3,4,5','6' => 'English','7' => '','8' => ''),
array('0' => '','1' => '','2' => '','3' => '','4' => 'Wasatch standard1.1','5' => 'Wasatch standard1.1','6' => '2','7' => 'Mathematics','8' =>''),
);
for($i=0;$i<count($array);$i++){
checkRecursivelyIfEmpty($array[$i],array('2'+$i,'3'+$i,'4'+$i,'5'+$i));
}
function checkRecursivelyIfEmpty($value,$sumValue){
foreach ($sumValue as $k => $v) {
if(empty($value[$v])){
throw new Exception("Error Processing Request");
}
}
}
The following function first checks whether the input is an array indeed, then checks for the indexes to be empty. If not, then it throws an exception. Furthermore, it traverses the array to see if there are inner arrays. If so, then it recursively checks them as well. After the function there is a quick demonstration of usage.
function checkThings($inputArray, $subArray) {
//If it is not an array, it does not have the given indexes
if (!is_array($inputArray)) {
return;
}
//throws exception if one of the elements in question is not empty
foreach ($subArray as $key) {
if ((isset($inputArray[$key])) && (!empty($inputArray[$key]))) {
throw new Exception("My Exception text");
}
}
//checks for inner occurrences
foreach ($inputArray as $key => $value) {
if (is_array($inputArray[$key])) {
checkThings($inputArray[$key], $subArray);
}
}
}
//Calls checkThings for all elements
for ($index = 0; $index < count($myArray); $index++) {
checkThings($myArray[$index], array($index + 2, $index + 3, $index + 4, $index + 5));
}
Use foreach and check using empty($value)
foreach ($array as $key => $value) {
$value = trim($value);
if (empty($value))
echo "$key empty <br/>";
else
echo "$key not empty <br/>";
}
Assuming the array is named $a you can use this code. The outer loops iterates over all the arrays. The inner loop iterates from $i+2 to $i+5 (in the case of $i=0, you get 2, 3, 4 and 5) on the sub arrays. The function empty() checks that the item is set and not equal to false (for instance, an empty string).
for($i=0; $i<count($a); $++)
for($j=$i+2; $j<$i+6; $j++)
if(empty($a[$i][$j]))
//Raise an error!
Related
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 array like this
Array (
[operator_15] => 3
[fiter_15] => 4
[operator_17] => 5
[fiter_17] => 5
[operator_19] => 4
[fiter_19] => 2
)
I want to separate this array in to 2 arrays:
key starting from fiter_
key starting from operator_
I used array filter and it doesn't work. any other option?
$array = array_filter(
$fitered_values,
function($key) {
return strpos($key, 'fiter_') === 0;
}
);
Just loop the array and substring what is before the _ with strpos and substr then you can filter them to a new array as this.
This method will also work with new array keys, see example:
$arr = array ( "operator_15" => 3,
"fiter_15" => 4,
"operator_17" => 5,
"fiter_17" => 5,
"somethingelse_12" => 99 // <--- Notice this line.
);
foreach($arr as $key => $val){
$subarr = substr($key,0, strpos($key, "_"));
$new[$subarr][$key] = $val;
}
var_dump($new);
output:
array(3) {
["operator"]=>
array(2) {
["operator_15"]=>
int(3)
["operator_17"]=>
int(5)
}
["fiter"]=>
array(2) {
["fiter_15"]=>
int(4)
["fiter_17"]=>
int(5)
}
["somethingelse"]=> // <-- is here now in it's own group with no code added
array(1) {
["somethingelse_12"]=>
int(99)
}
}
Give a try with below and see if its solve your problem
$array = array (
'operator_15' => 3,
'fiter_15' => 4,
'operator_17' => 5,
'fiter_17' => 5,
'operator_19' => 4,
'fiter_19' => 2 );
$operator=array();
$filter=array();
foreach($array as $key => $value){
if (strpos($key, 'operator_') !== false) {
$operator[$key] = $value;
}
if (strpos($key, 'fiter_') !== false) {
$filter[$key] = $value;
}
}
print_r($operator);
print_r($filter);
While iterating your array, populate a new array with first level (grouping) keys based on the prefix (substring before the underscore), then push the original associative data into that group.
Code: (Demo)
$result = [];
foreach ($array as $k => $v) {
$result[strtok($k, '_')][$k] = $v;
}
var_export($result);
It is suboptimal programming to declare individual variables because this removes the convenience of being able to easily iterate related data (related by structure).
The above snippet will allow you to iterate $result and access all data sets or you can individually access a particular subset like $result['fiter'].
This is a working example:
$a = array ( 'operator_15' => 3, 'fiter_15' => 4, 'operator_17' => 5, 'fiter_17' => 5, 'operator_19' => 4, 'fiter_19' => 2 );
$fiter_array = array();
$operator_array = array();
foreach($a as $key => $val)
{
if(strpos($key, 'fiter') !== false)
{
array_push($fiter_array, $a[$key]);
// or if you want to maintain the key
$fiter_array[$key] = $val;
}
else
{
array_push($operator_array, $a[$key]);
// or if you want to maintain the key
$operator_array[$key] = $val;
}
};
var_dump($fiter_array);
var_dump($operator_array);
I created multiple dimensional array and tried to update count value for certain condition as below but not working.
$test[] = [
'firstNm' => 'luke'
,'lastNm' => 'Lee'
,'count' => 10
];
$test[] = [
'firstNm' => 'John'
,'lastNm' => 'Doe'
,'count' => 20
];
foreach ($test as $test01)
{
if ($test01['firstNm'] === 'John'){
$test01['count'] += 70 ;}
}
Looking forward to your help.
Thank you.
Actually you are increasing the value but missing to reasign to the same array. Try this one.
$test[] = [
'firstNm' => 'luke'
,'lastNm' => 'Lee'
,'count' => 10
];
$test[] = [
'firstNm' => 'John'
,'lastNm' => 'Doe'
,'count' => 20
];
foreach ($test as $key => $test01)
{
if ($test01['firstNm'] === 'John'){
$test[$key]['count'] += 70 ;
}
}
print_r($test);
Borrowing from this answer, which cites the PHP manual page for foreach:
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.1
So you could iterate over the array elements by-reference:
foreach ($test as &$test01)
{
if ($test01['firstNm'] === 'John'){
$test01['count'] += 70 ;
}
}
See this illustrated on Teh Playground.
Otherwise you can iterate using the key=>value syntax:
foreach ($test as $index=>$test01)
{
if ($test01['firstNm'] === 'John'){
$test[$index]['count'] += 70 ;
}
}
i have array like this
<?php
$array =
array
(
array (
0 => 1,
1 => 'php',
2 => 11,
3 => 11,
4 => 11,
5 => 11,
6 => 11,
),
array (
0 => 1,
1 => 'php',
2 => 11,
3 => 11,
4 => 11,
5 => 11,
6 => ,
),
);
and i want to search in this multi-array to find if the key [6] => is empty.if it was empty in any array return false so how to do this
foreach($array as $item)
{
foreach($item as $key=>$value)
{
print($key);
if($key=="6" && $value==NULL)
{
echo "found";
return false;
}else{
echo "not found";
return true;
}
}
}
$empty = false;
foreach($array as $item)
{
if(empty($item[6]))
{
$empty=true;
break;
}
}
return $empty;
First, it's recommended to use only one return in a function, so define a boolean value, and turn it to TRUE when the condition satisfies.
Second, use break to stop the cycle(s) running (saves runtime)
http://php.net/manual/en/control-structures.break.php
Third, check keys and values appropriately. Your keys are numeric and you are comparing to a string "6". Use empty() if you are interested in that the value is an empty-ish value. Be aware that a numeric zero is an empty value. If you are specifically interested in NULL value, use === operator
http://php.net/manual/en/function.empty.php
http://php.net/manual/en/language.operators.comparison.php
+1 See Yoda-style conditions
http://en.wikipedia.org/wiki/Yoda_conditions
++1 Use K&R style indent, or don't use it. But do not try! ;)
http://en.wikipedia.org/wiki/Indent_style#K.26R_style
$found = false;
foreach ($array as $item) {
foreach ($item as $key => $value) {
print($key);
if (6 == $key && NULL === $value) { // or use 'empty($value)'
echo "found";
$found = true;
break 2;
} else {
echo "not found";
}
}
}
return !$found;
Here's an alternate for PHP >= 5.5.0 that checks for '', 0, null and false:
return !array_diff($six = array_column($array, 6), array_filter($six));
I have a nested array in which I want to display a subset of results. For example, on the array below I want to loop through all the values in nested array[1].
Array
(
[0] => Array
(
[0] => one
[1] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
)
[1] => Array
(
[0] => two
[1] => Array
(
[0] => 4
[1] => 5
[2] => 6
)
)
[2] => Array
(
[0] => three
[1] => Array
(
[0] => 7
[1] => 8
[2] => 9
)
)
)
I was trying to use the foreach function but I cannot seem to get this to work. This was my original syntax (though I realise it is wrong).
$tmpArray = array(array("one",array(1,2,3)),array("two",array(4,5,6)),array("three",array(7,8,9)));
foreach ($tmpArray[1] as $value) {
echo $value;
}
I was trying to avoid a variable compare on whether the key is the same as the key I want to search, i.e.
foreach ($tmpArray as $key => $value) {
if ($key == 1) {
echo $value;
}
}
Any ideas?
If you know the number of levels in nested arrays you can simply do nested loops. Like so:
// Scan through outer loop
foreach ($tmpArray as $innerArray) {
// Check type
if (is_array($innerArray)){
// Scan through inner loop
foreach ($innerArray as $value) {
echo $value;
}
}else{
// one, two, three
echo $innerArray;
}
}
if you do not know the depth of array you need to use recursion. See example below:
// Multi-dementional Source Array
$tmpArray = array(
array("one", array(1, 2, 3)),
array("two", array(4, 5, 6)),
array("three", array(
7,
8,
array("four", 9, 10)
))
);
// Output array
displayArrayRecursively($tmpArray);
/**
* Recursive function to display members of array with indentation
*
* #param array $arr Array to process
* #param string $indent indentation string
*/
function displayArrayRecursively($arr, $indent='') {
if ($arr) {
foreach ($arr as $value) {
if (is_array($value)) {
//
displayArrayRecursively($value, $indent . '--');
} else {
// Output
echo "$indent $value \n";
}
}
}
}
The code below with display only nested array with values for your specific case (3rd level only)
$tmpArray = array(
array("one", array(1, 2, 3)),
array("two", array(4, 5, 6)),
array("three", array(7, 8, 9))
);
// Scan through outer loop
foreach ($tmpArray as $inner) {
// Check type
if (is_array($inner)) {
// Scan through inner loop
foreach ($inner[1] as $value) {
echo "$value \n";
}
}
}
foreach ($tmpArray as $innerArray) {
// Check type
if (is_array($innerArray)){
// Scan through inner loop
foreach ($innerArray as $value) {
echo $value;
}
}else{
// one, two, three
echo $innerArray;
}
}
Both syntaxes are correct. But the result would be Array. You probably want to do something like this:
foreach ($tmpArray[1] as $value) {
echo $value[0];
foreach($value[1] as $val){
echo $val;
}
}
This will print out the string "two" ($value[0]) and the integers 4, 5 and 6 from the array ($value[1]).
As I understand , all of previous answers , does not make an Array output,
In my case :
I have a model with parent-children structure (simplified code here):
public function parent(){
return $this->belongsTo('App\Models\Accounting\accounting_coding', 'parent_id');
}
public function children()
{
return $this->hasMany('App\Models\Accounting\accounting_coding', 'parent_id');
}
and if you want to have all of children IDs as an Array , This approach is fine and working for me :
public function allChildren()
{
$allChildren = [];
if ($this->has_branch) {
foreach ($this->children as $child) {
$subChildren = $child->allChildren();
if (count($subChildren) == 1) {
$allChildren [] = $subChildren[0];
} else if (count($subChildren) > 1) {
$allChildren += $subChildren;
}
}
}
$allChildren [] = $this->id;//adds self Id to children Id list
return $allChildren;
}
the allChildren() returns , all of childrens as a simple Array .
I had a nested array of values and needed to make sure that none of those values contained &, so I created a recursive function.
function escape($value)
{
// return result for non-arrays
if (!is_array($value)) {
return str_replace('&', '&', $value);
}
// here we handle arrays
foreach ($value as $key => $item) {
$value[$key] = escape($item);
}
return $value;
}
// example usage
$array = ['A' => '&', 'B' => 'Test'];
$result = escape($array);
print_r($result);
// $result: ['A' => '&', 'B' => 'Test'];
array(
"IT"=>
array(
array('id'=>888,'First_name'=>'Raahul','Last_name'=>'Pandey'),
array('id'=>656,'First_name'=>'Ravi','Last_name'=>'Teja'),
array('id'=>998,'First_name'=>'HRX','Last_name'=>'HRITHIK')
),
// array(
"DS"=>
array(
array('id'=>87,'First_name'=>'kalia','Last_name'=>'Pandey'),
array('id'=>6576,'First_name'=>'Raunk','Last_name'=>'Teja'),
array('id'=>9987,'First_name'=>'Krish','Last_name'=>'HRITHIK')
)
// )
)
);
// echo "";
// print_r($a);
echo "";
print_r($a);
?>
////how to get id in place of index value....