Determine whether array key value is blank - php

I have an array like below, as you can see the last array [adad] value is blank, how can I write an if statement to tell whether this is blank.
Array
(
[K] => Array
(
[0] => mabel__chan
[1] => mabel chan
)
[B] => Array
(
[0] => kieron br
)
[C] => Array
(
[0] => a br
[1] => a
)
[adad] => Array
(
[0] =>
)
)
I have tried doing this
if (count(array_filter($array)) == 0) {}
Pseudo code
if(array[key] == blank) {
echo "is blank";
} else {
echo "isn't blank";
}
**PHP Script this is how I get my data from mongoDB*
The answer below is working correctly when I use echos but now when I'm trying to push into new arrays its broken somewhere I get no data back anymore.
$col = "A" . $user->agencyID;
$db = $m->rules;
$collection = $db->$col;
$id = $_POST['ruleID'];
$search = array(
'_id' => new MongoId($id)
);
$cursor = $collection->find($search);
$validTagsArray = array();
$validArray = array();
foreach ($cursor as $key => $value) {
$temp = array_walk($array, function($v, $k) {
if (count(array_filter($v)) === 0) {
foreach ($value['AutoFix'] as $keyTwo => $valTwo) {
$x = 0;
$validTagsArray['data'][] = array($keyTwo, $x);
}
} else {
foreach ($value['AutoFix'] as $keyTwo => $valTwo) {
$x = 0;
foreach ($valTwo as $key => $value) {
$x++;
}
$validTagsArray['data'][] = array($keyTwo, $x);
}
}
});
}
echo json_encode($validTagsArray);

You can try this -
$array = array
(
'K' => array('0' => 'mabel__chan','1' => 'mabel chan'),
'B' => array('0' => 'kieron br'),
'C' => array('0' => 'a br', '1' => 'a'),
'adad' => array('0' => '')
);
$temp = array_walk($array, function($v, $k) {
if(count(array_filter($v)) === 0) { // check the count of non-empty elements in the sub array
echo $k . ' is empty';
}
});
Output
adad is empty

You can write as:
if([adad][0]== " ")
{
}
You can also try this :
foreach($array as $key=>$value){
if(empty($value))
echo "empty";
}

Related

array difference returning edited values

The following code checks the first array(parameter1) aginst the second array(parameter2) and returns an array that tells which elements were modified.
$array_data = array(
"studDetails" => array(
"studDet" => array(
"studClass" => "V",
),
),
"email" => "kavya#opspl.com",
"systemNames" => array("EMR"),
);
$array_edited = $array_data;
//EDITING
$array_edited['email'] = "kam";
$array_edited['studDetails']['studDet']['studClass'] = "VV";
echo "<pre>";
print_r(array_diff_assoc2_deep($array_edited, $array_data));
function array_diff_assoc2_deep($array_edited, $array_data)
{
$difference = array();
foreach ($array_edited as $row => $value) {
if (!isset($array_data[$row]) && !empty($value)) {
$difference['added'][$row] = $value;
} else if (is_array($array_edited[$row]) && is_array($array_data[$row])) {
$difference[$row] = array_diff_assoc2_deep($array_edited[$row], $array_data[$row]);
} else if ((string)$value != (string)$array_data[$row]) {
$difference['edited'][$row] = array("old" => $array_data[$row], "new" => $value);
}
}
$difference = array_filter($difference);
return $difference;
}
OUTPUT:
Array (
[studDetails] => Array (
[studDet] => Array (
[edited] => Array (
[studClass] => Array (
[old] => V
[new] => VV
)
)
)
)
[edited] => Array (
[email] => Array (
[old] => kavya#opspl.com
[new] => kam
)
)
)
I want the output to be in a single edited key no matter how many internal arrays are there.
DESIRED OUTPUT:
Array (
[edited] => Array (
[email] => Array (
[old] => kavya#opspl.com
[new] => kam
)
[studClass] => Array (
[old] => V
[new] => VV
)
)
)
The reason this happens is the recursive call:
$difference[$row] = array_diff_assoc2_deep($array_edited[$row], $array_data[$row]);
With this line, you put each recursive comparison result into a separate key.
If you don't do this but keep the resulting array flat, you'll get what you want:
function array_diff_assoc2_deep($array_edited, $array_data, $difference = array())
{
foreach ($array_edited as $row => $value) {
if (!isset($array_data[$row]) && !empty($value)) {
$difference['added'][$row] = $value;
} else if (is_array($array_edited[$row]) && is_array($array_data[$row])) {
$difference = array_diff_assoc2_deep($array_edited[$row], $array_data[$row], $difference);
} else if ((string)$value != (string)$array_data[$row]) {
$difference['edited'][$row] = array("old" => $array_data[$row], "new" => $value);
}
}
$difference = array_filter($difference);
return $difference;
}
Three lines have changed:
function array_diff_assoc2_deep($array_edited, $array_data, $difference = array())
//{
## REMOVED: $difference = array();
// foreach ($array_edited as $row => $value) {
// if (!isset($array_data[$row]) && !empty($value)) {
// $difference['added'][$row] = $value;
// } else if (is_array($array_edited[$row]) && is_array($array_data[$row])) {
$difference = array_diff_assoc2_deep($array_edited[$row], $array_data[$row], $difference);
// } else if ((string)$value != (string)$array_data[$row]) {
// $difference['edited'][$row] = array("old" => $array_data[$row], "new" => $value);
// }
//
// }
// $difference = array_filter($difference);
// return $difference;
//}
You can see the output here.

combine arrays and concat value?

Little complex to explain , so here is simple concrete exemple :
array 1 :
Array
(
[4] => bim
[5] => pow
[6] => foo
)
array 2 :
Array
(
[n] => Array
(
[0] => 1
)
[m] => Array
(
[0] => 1
[1] => 2
)
[l] => Array
(
[0] => 1
[1] => 4
[2] => 64
)
And i need to output an array 3 ,
array expected :
Array
(
[bim] => n-1
[pow] => Array
(
[0] => m-1
[1] => m-2
)
[foo] => Array
(
[0] => l-1
[1] => l-4
[2] => l-64
)
Final echoing OUTPUT expected:
bim n-1 , pow m-1 m-2 ,foo l-1 l-4 l-64 ,
I tried this but seems pity:
foreach($array2 as $k1 =>$v1){
foreach($array2[$k1] as $k => $v){
$k[] = $k1.'_'.$v);
}
foreach($array1 as $res =>$val){
$val = $array2;
}
Thanks for helps,
Jess
CHALLENGE ACCEPTED
<?php
$a = array(
4 => 'bim',
5 => 'pow',
6 => 'foo',
);
$b = array(
'n' => array(1),
'm' => array(1, 2),
'l' => array(1, 4, 64),
);
$len = count($a);
$result = array();
$aVals = array_values($a);
$bKeys = array_keys($b);
$bVals = array_values($b);
for ($i = 0; $i < $len; $i++) {
$combined = array();
$key = $aVals[$i];
$prefix = $bKeys[$i];
$items = $bVals[$i];
foreach ($items as $item) {
$combined[] = sprintf('%s-%d', $prefix, $item);
};
if (count($combined) === 1) {
$combined = $combined[0];
}
$result[$key] = $combined;
}
var_dump($result);
?>
Your code may be very easy. For example, assuming arrays:
$one = Array
(
4 => 'bim',
5 => 'pow',
6 => 'foo'
);
$two = Array
(
'n' => Array
(
0 => 1
),
'm' => Array
(
0 => 1,
1 => 2
),
'l' => Array
(
0 => 1,
1 => 4,
2 => 64
)
);
You may get your result with:
$result = [];
while((list($oneKey, $oneValue) = each($one)) &&
(list($twoKey, $twoValue) = each($two)))
{
$result[$oneValue] = array_map(function($item) use ($twoKey)
{
return $twoKey.'-'.$item;
}, $twoValue);
};
-check this demo Note, that code above will not make single-element array as single element. If that is needed, just add:
$result = array_map(function($item)
{
return count($item)>1?$item:array_shift($item);
}, $result);
Version of this solution for PHP4>=4.3, PHP5>=5.0 you can find here
Update: if you need only string, then use this (cross-version):
$result = array();
while((list($oneKey, $oneValue) = each($one)) &&
(list($twoKey, $twoValue) = each($two)))
{
$temp = array();
foreach($twoValue as $item)
{
$temp[] = $twoKey.'-'.$item;
}
$result[] = $oneValue.' '.join(' ', $temp);
};
$result = join(' ', $result);
As a solution to your problem please try executing following code snippet
<?php
$a=array(4=>'bim',5=>'pow',6=>'foo');
$b=array('n'=>array(1),'m'=>array(1,2),'l'=>array(1,4,64));
$keys=array_values($a);
$values=array();
foreach($b as $key=>$value)
{
if(is_array($value) && !empty($value))
{
foreach($value as $k=>$val)
{
if($key=='n')
{
$values[$key]=$key.'-'.$val;
}
else
{
$values[$key][]=$key.'-'.$val;
}
}
}
}
$result=array_combine($keys,$values);
echo '<pre>';
print_r($result);
?>
The logic behind should be clear by reading the code comments.
Here's a demo # PHPFiddle.
//omitted array declarations
$output = array();
//variables to shorten things in the loop
$val1 = array_values($array1);
$keys2 = array_keys($array2);
$vals2 = array_values($array2);
//iterating over each element of the first array
for($i = 0; $i < count($array1); $i++) {
//if the second array has multiple values at the same index
//as the first array things will be handled differently
if(count($vals2[$i]) > 1) {
$tempArr = array();
//iterating over each element of the second array
//at the specified index
foreach($vals2[$i] as $val) {
//we push each element into the temporary array
//(in the form of "keyOfArray2-value"
array_push($tempArr, $keys2[$i] . "-" . $val);
}
//finally assign it to our output array
$output[$val1[$i]] = $tempArr;
} else {
//when there is only one sub-element in array2
//we can assign the output directly, as you don't want an array in this case
$output[$val1[$i]] = $keys2[$i] . "-" . $vals2[$i][0];
}
}
var_dump($output);
Output:
Array (
["bim"]=> "n-1"
["pow"]=> Array (
[0]=> "m-1"
[1]=> "m-2"
)
["foo"]=> Array (
[0]=> "l-1"
[1]=> "l-4"
[2]=> "l-64"
)
)
Concerning your final output you may do something like
$final = "";
//$output can be obtained by any method of the other answers,
//not just with the method i posted above
foreach($output as $key=>$value) {
$final .= $key . " ";
if(count($value) > 1) {
$final .= implode($value, " ") .", ";
} else {
$final .= $value . ", ";
}
}
$final = rtrim($final, ", ");
This will echo bim n-1, pow m-1 m-2, foo l-1 l-4 l-64.

Group pairs in array

I'm trying to group airlines with relations into single chains.
Array
(
[0] => Array
(
[0] => Aeroflot
[1] => S7
[2] => Transaero
)
[1] => Array
(
[0] => Alitalia
[1] => Lufthansa
)
[2] => Array
(
[0] => Transaero
[1] => United
)
[3] => Array
(
[0] => United
[1] => Alitalia
)
[4] => Array
(
[0] => Volotea
[1] => Iberia
)
[5] => Array
(
[0] => Transaero
[1] => Aeroflot
)
)
From that array I need to find connections between elements and combine it to groups. Expected results:
Array
(
[0] => Array
(
[0] => Aeroflot
[1] => S7
[2] => Transaero
[3] => United
[4] => Alitalia
[5] => Lufthansa
)
[1] => Array
(
[0] => Volotea
[1] => Iberia
)
)
Can anyone help with that? I've tried a dozen of ways but still get no success.
The most closest way I've tried which works but not in all cases:
function array_searchRecursive($needle,$haystack) {
foreach($haystack as $key=>$value) {
$current_key=$key;
if($needle===$value OR (is_array($value) && array_searchRecursive($needle,$value) !== false)) {
return $current_key;
}
}
return false;
}
foreach ($newarr as $key => $airlines)
{
foreach ($airlines as $lastkey => $airline)
{
$index = array_searchRecursive($airline,$newarr);
echo $airline.$index."\n";
if ($index !== false)
{
$newarr[$index] = array_merge($newarr[$index],$airlines);
$lastarr[] = $index;
}
}
}
But it doesn't match all values in array.
Recursive function will help you. You are welcome )
$arr = array(
array('Aeroflot','S7','Transaero'),
array('Alitalia','Lufthansa'),
array('Transaero','United'),
array('United','Alitalia'),
array('Volotea','Iberia'),
array('Transaero','Aeroflot')
);
function getConnections($arr,$curr_line_n=0,$num=0) {
for($i=0;$i<count($arr[$curr_line_n]);$i++) {
$cur_air_name = $arr[$curr_line_n][$i];
for($k=$curr_line_n+1; $k<count($arr); $k++) {
for($l=0;$l<count($arr[$k]);$l++) {
if ($arr[$k][$l]==$cur_air_name) {
$arr[$curr_line_n] = array_values(array_unique(array_merge($arr[$curr_line_n],$arr[$k])));
array_splice($arr,$k,1);
$num++;
$arr = getConnections($arr,$curr_line_n,$num);
}
}
}
}
$num++;
$curr_line_n++;
if ($curr_line_n!=count($arr)) {
$arr = getConnections($arr,$curr_line_n,$num);
}
return $arr;
}
print_r(getConnections($arr));
As per your example you are just grouping sub arrays by taking first sub array as reference. for example if you have any elements common in first sub array and in subsequent sub arrays then you combine them into one sub array.
<?php
$arr = array(
array('a', 'b', 'c', 'd'),
array('d', 't'),
array('t', 'f'),
array('k', 'o'),
array('p', 'z')
);
$arr_implode = array();
foreach ($arr as $key => $value) {
if (is_array($value)) {
$arr_implode[$key] = implode('', $value);
} else {
$arr_implode[$key] = $value;
}
}
$arr_key = array();
$result = array();
$count = count($arr_implode);
$tempj = 0;
for ($i = 0; $i <= $count; $i++) {
$flag = FALSE;
for ($j = ($i + 1); $j < $count; $j++) {
similar_text($arr_implode[$i], $arr_implode[$j], $percent);
if ($percent > 0) {
$result[] = array_merge($arr[$i],$arr[$j]);
break;
} else {
$result[] = $arr[$j];
break;
}
}
}
foreach($result as $key => $val){
$result[$key] = array_unique($val);
}
echo "<pre>";
print_r($result);
echo "</pre>";
?>
Try this code.
$arr = [
['Aeroflot', 'S7', 'Transaero'],
['Alitalia', 'Lufthansa'],
['Transaero', 'United'],
['United', 'Alitalia'],
['Volotea', 'Iberia'],
['Transaero', 'Aeroflot']
];
$hash = [];
$result = [];
foreach($arr as $set){
foreach($set as $el){
if(!$hash[$el]) $hash[$el] = [] ;
$hash[$el] = array_merge($hash[$el], $set);
}
}
function merge_connections(&$h, $key){
if(!$h[$key]) return [];
$data = [$key];
$rels = $h[$key];
unset($h[$key]);
foreach($rels as $rel){
if($rel==$key) continue;
$data = array_merge($data, merge_connections($h, $rel));
}
return $data;
}
foreach(array_keys($hash) as $company){
if(!$hash[$company]) continue;
array_push($result, merge_connections($hash, $company));
}
print_r($result);

Deleting redundant data inside an array

I have a problem, I have this result below and I want to remove the same timestamp.
Sample Result:
Array
(
[0] => [1341100800000, 0]
[1] => [1341100800000,85]
[2] => [1343779200000,54]
[3] => [1343779200000, 0]
)
Expecting Output
Array
(
[0] => [1341100800000,85]
[1] => [1343779200000,54]
)
I'm thinking of using explode then substr function to get the value. Here is what I came up so far..
$explode = array();
foreach($string_format as $key => $value) {
$explode[] = explode(',', substr($value, 1));
if((isset($explode[0]) && $explode[0][0] == $explode[1][0])) {
unset($explode[0]);
}
//print_r($explode);
}
wouldn't this be a good use of http://us2.php.net/manual/en/function.array-unique.php
Script:
foreach($string_format as $key => $value) {
$explode = explode(',', $value);
$unique[$explode[0]] = $value;
}
Input:
$string_format = array('0' => '1341100800000, 0',
'1' => '1341100800000,85',
'2' => '1343779200000,54',
'3' => '1343779200000, 0');
Output:
$unique =
Array
(
[1341100800000] => 1341100800000,85
[1343779200000] => 1343779200000, 0
)
This should work fine :)
$explode = array();
$timestmp = array();
foreach($string_format as $key => $value) {
$explode[$key] = explode(',', substr($value, 1));
if( in_array( $explode[$key][0], $timestmp)) {
unset ($explode[$key]);
} else {
$timestmp[]= $explode[$key][0];
}
}

count of duplicate elements in an array in php

Hi,
How can we find the count of duplicate elements in a multidimensional array ?
I have an array like this
Array
(
[0] => Array
(
[lid] => 192
[lname] => sdsss
)
[1] => Array
(
[lid] => 202
[lname] => testing
)
[2] => Array
(
[lid] => 192
[lname] => sdsss
)
[3] => Array
(
[lid] => 202
[lname] => testing
)
)
How to find the count of each elements ?
i.e, count of entries with id 192,202 etc
You can adopt this trick; map each item of the array (which is an array itself) to its respective ['lid'] member and then use array_count_value() to do the counting for you.
array_count_values(array_map(function($item) {
return $item['lid'];
}, $arr);
Plus, it's a one-liner, thus adding to elite hacker status.
Update
Since 5.5 you can shorten it to:
array_count_values(array_column($arr, 'lid'));
foreach ($array as $value)
{
$numbers[$value[lid]]++;
}
foreach ($numbers as $key => $value)
{
echo 'numbers of '.$key.' equal '.$value.'<br/>';
}
Following code will count duplicate element of an array.Please review it and try this code
$arrayChars=array("green","red","yellow","green","red","yellow","green");
$arrLength=count($arrayChars);
$elementCount=array();
for($i=0;$i<$arrLength-1;$i++)
{
$key=$arrayChars[$i];
if($elementCount[$key]>=1)
{
$elementCount[$key]++;
} else {
$elementCount[$key]=1;
}
}
echo "<pre>";
print_r($elementCount);
OUTPUT:
Array
(
[green] => 3
[red] => 2
[yellow] => 2
)
You can also view similar questions with array handling on following link
http://solvemyquest.com/count-duplicant-element-array-php-without-using-built-function/
The following code will get the counts for all of them - anything > 1 at the end will be repeated.
<?php
$lidCount = array();
$lnameCount = array();
foreach ($yourArray as $arr) {
if (isset($lidCount[$arr['lid']])) {
$lidCount[$arr['lid']]++;
} else {
$lidCount[$arr['lid']] = 1;
}
if (isset($lnameCount [$arr['lname']])) {
$lnameCount [$arr['lname']]++;
} else {
$lnameCount [$arr['lname']] = 1;
}
}
$array = array('192', '202', '192', '202');
print_r(array_count_values($array));
$orders = array(
array(
'lid' => '',
'lname' => '',
))....
$foundIds = array();
foreach ( $orders as $index => $order )
{
if ( isset( $foundIds[$order['lid']] ) )
{
$orders[$index]['is_dupe'] = true;
$orders[$foundIds[$order['lid']]]['is_dupe'] = true;
} else {
$orders[$index]['is_dupe'] = false;
}
$foundIds[$order['lid']] = $index;
}
Try this code :
$array_count = array();
foreach ($array as $arr) :
if (in_array($arr, $array_count)) {
foreach ($array_count as $key => $count) :
if ($key == $arr) {
$array_count[$key]++;
break;
}
endforeach;
} else {
$array_count[$arr] = 1;
}
endforeach;
Check with in_array() function.

Categories