check for empty array and remove empty array - php

i have 100 values in array ,need to check first ten values are not empty and all elements should be same count if not unset the values ,i using "|" for combing all the values ,
I have all the values implode with "|" below is the function which im using im not getting final results as required ,finalvalues is given below ,can you please help fixing this issue
finalvalues =array(
"3" =>"Education|Category|Roles|Industry|Address|Email|Phone|Mobile",
"4" => "Bsc|computer|SE|Computers||test#test.com|123123132|123234234234"
);
$values = array(
"0"=> "Computer Student History",
"1"=> "Computer Student History",
"2"=> "Computer Student History|batch number",
"3" => "| | | | | | | | | | | | | | | | ",
"4" => "Education|Category|Roles|Industry|Address|Email|Phone|Mobile",
"5" => "Bsc|computer|SE|Computers||test#test.com|123123132|123234234234"
);
$newVal = array();
foreach ($values as $key => $val) { //$values it is..
$prevalues = explode('|', $val);
$finalvalue = array_empty($prevalues ,$full_null=true);
if($finalvalue == 1){
unset($prevalues); //why??
}else{
$vales = implode('|', $prevalues);
$newVal[$key] = $vales; //use $key, to preserve the keys here..
}
}
print_r($newVal); //output
function array_empty($ary, $full_null=false){
unset($prevKey);
$count = array();
$null_count = 0;
$ary_count = count($ary);
if ($ary_count == 1) //this means there was no '|', hence no split.
return 1;
foreach($array_keys($ary) as $value){
// echo $value;
//trying check if first value is less then second value unset array similar second is less then third value unset second .. so the all the array values is same count
$count[$value] = count($ary[$value]);
if (isset($prevKey) && $count[$prevKey] !== $count[$value]) {
//unset($array[$prevKey]);
return 1;
}
if($value == NULL || trim($value) == "" ){ // trim(..) was what you wanted.
$null_count++;
}
}
if($full_null == true){
if($null_count == $ary_count){
return 1;
}else{
return 0;
}
}
}

This should help you (with inline comments):
$newVal = array();
foreach ($values as $key => $val) { //$values it is..
$prevalues = explode('|', $val);
$finalvalue = array_empty($prevalues ,$full_null=true);
if($finalvalue == 1){
unset($prevalues); //why??
}else{
$vales = implode('|', $prevalues);
$newVal[$key] = $vales; //use $key, to preserve the keys here..
}
}
print_r($newVal); //output
function array_empty($ary, $full_null=false){
$null_count = 0;
$ary_count = count($ary);
if ($ary_count == 1) //this means there was no '|', hence no split.
return 1;
foreach($ary as $value){
// echo $value;
if($value == NULL || trim($value) == "" ){ // trim(..) was what you wanted.
$null_count++;
}
}
if($full_null == true){
if($null_count == $ary_count){
return 1;
}else{
return 0;
}
}
}

Here are some much simpler, not crazy ways
PHP 5.3+
$final = array_filter(
$values,
function( $v ){
return
preg_replace( '~\s*\|\s*~', '', $v ) &&
count( explode( '|', $v ) ) === 8;
}
);
PHP < 5.3
This edits the $values array directly
foreach( $values as $k => $value ) {
if ( preg_replace( '~\s*\|\s*~', '', $value ) == '' || count( explode( '|', $value ) ) !== 8 ) {
unset( $values[$k] );
}
}

Related

PHP function - How to take three fields and perform and action when the first, 2nd and last field are the same but on different rows of a file

I have file that is delimetered by a comma like below
Big2,red,0,Y
Big2,blue,0,N
Big2,green,1,N
Big6,red,0,Y
Big6,blue,0,N
Big6,green,1,N
Big6,yellow,0,Y
Big6,black,0,Y
Following is the code I used to read the file
$file_content = explode("\n",(file_get_contents("inven.csv")));
foreach ($file_content as $key => $value) {
$value = str_replace(array('\'', '"'), '', $value);
$line_records = explode(',', $value);
$reference = trim($line_records[0]);
$option = trim($line_records[1]);
$quantity = trim($line_records[2]);
$discontinued = trim($line_records[3]);
}
I want to check for the following condition and perform some action
If the 1st, 2nd and 4th field are the same for all lines
If all "Big2" rows have the 3rd field = 0 and the 4th field = Y
Hope this solves your problem
$references = $options =$quantities = $status = array();
$file_content = explode("\n",(file_get_contents("inven.csv")));
foreach ($file_content as $key => $value) {
$value = str_replace(array('\'', '"'), '', $value);
$line_records = explode(',', $value);
$references[] = trim($line_records[0]);
echo end($references);
$options[] = trim($line_records[1]);
echo end($options);
$quantities[] = trim($line_records[2]);
echo end($quantities);
$status[] = trim($line_records[3]);
echo end($status);
}
$flag = true;
foreach(array_combine($references, $quantities, $status) as $ref => $quantity => $stat) { // foreach line throws and error
if($ref == 'Big2') {
if($quantity != 0 || $stat != 'Y'){
$flag = false;
break;
}
}
}
if (count(array_unique($references)) === 1 && count(array_unique($options))==1 && count(array_unique($status))==1) {
//Do action if the 1st, 2nd and 4th field are the same for all lines
}
if ($flag) {
//Do action if all "Big2" rows have the 3rd field = 0 and the 4th field = Y
}

How to splitting words match by patterns with PHP

I have an array of words. e.g.,
$pattern = ['in', 'do', 'mie', 'indo'];
I wanna split a words match by the patterns to some ways.
input =
indomie
to output =
$ in, do, mie
$ indo, mie
any suggests?
*ps sorry for bad english. thank you very much!
it was an very interesting question.
Input:-
$inputSting = "indomie";
$pattern = ['in', 'do', 'mie', 'indo','dom','ie','indomi','e'];
Output:-
in,do,mie
in,dom,ie
indo,mie
indomi,e
Approach to this challenge
Get the pattern string length
Get the all the possible combination of matrix
Check whether the pattern matching.
if i understand your question correctly then above #V. Prince answer will work only for finding max two pattern.
function sampling($chars, $size, $combinations = array()) {
if (empty($combinations)) {
$combinations = $chars;
}
if ($size == 1) {
return $combinations;
}
$new_combinations = array();
foreach ($combinations as $combination) {
foreach ($chars as $char) {
$new_combinations[] = $combination . $char;
}
}
return sampling($chars, $size - 1, $new_combinations);
}
function splitbyPattern($inputSting, $pattern)
{
$patternLength= array();
// Get the each pattern string Length
foreach ($pattern as $length) {
if (!in_array(strlen($length), $patternLength))
{
array_push($patternLength,strlen($length));
}
}
// Get all the matrix combination of pattern string length to check the probablbe match
$combination = sampling($patternLength, count($patternLength));
$MatchOutput=Array();
foreach ($combination as $comp) {
$intlen=0;
$MatchNotfound = true;
$value="";
// Loop Through the each probable combination
foreach (str_split($comp,1) as $length) {
if($intlen<=strlen($inputSting))
{
// Check whether the pattern existing
if(in_array(substr($inputSting,$intlen,$length),$pattern))
{
$value = $value.substr($inputSting,$intlen,$length).',';
}
else
{
$MatchNotfound = false;
break;
}
}
else
{
break;
}
$intlen = $intlen+$length;
}
if($MatchNotfound)
{
array_push($MatchOutput,substr($value,0,strlen($value)-1));
}
}
return array_unique($MatchOutput);
}
$inputSting = "indomie";
$pattern = ['in', 'do', 'mie', 'indo','dom','ie','indomi','e'];
$output = splitbyPattern($inputSting,$pattern);
foreach($output as $out)
{
echo $out."<br>";
}
?>
try this one..
and if this solves your concern. try to understand it.
Goodluck.
<?php
function splitString( $pattern, $string ){
$finalResult = $semiResult = $output = array();
$cnt = 0;
# first loop of patterns
foreach( $pattern as $key => $value ){
$cnt++;
if( strpos( $string, $value ) !== false ){
if( implode("",$output) != $string ){
$output[] = $value;
if( $cnt == count($pattern) ) $semiResult[] = implode( ",", $output );
}else{
$semiResult[] = implode( ",", $output );
$output = array();
$output[] = $value;
if( implode("",$output) != $string ){
$semiResult[] = implode( ",", $output );
}
}
}
}
# second loop of patterns
foreach( $semiResult as $key => $value ){
$stackString = explode(",", $value);
/* if value is not yet equal to given string loop the pattern again */
if( str_replace(",", "", $value) != $string ){
foreach( $pattern as $key => $value ){
if( !strpos(' '.implode("", $stackString), $value) ){
$stackString[] = $value;
}
}
if( implode("", $stackString) == $string ) $finalResult[] = implode(",", $stackString); # if result equal to given string
}else{
$finalResult[] = $value; # if value is already equal to given string
}
}
return $finalResult;
}
$pattern = array('in','do','mie','indo','mi','e', 'i');
$string = 'indomie';
var_dump( '<pre>',splitString( $pattern, $string ) );
?>

How to get all values between two array values in php?

How can I find all values between two array items (including start and end value)?
Example:
array('3X' => '3X','EX'=> 'EX','VG'=>'VG','G'=>'G','F'=>'F','P'=>'P')
Input: $arr, 'EX', 'F'
Output: 'EX', 'VG', 'G', 'F'
Thanks in advance..
$array = array('3X' => '3X','EX'=> 'EX','VG'=>'VG','G'=>'G','F'=>'F','P'=>'P');
$start = "3X";
$end ="F";
$new_array = [];
$i=0;$go=false;
foreach ($array as $element) {
if($go){
$new_array[$i] = $element;
$i++;
}
if($element==$start){
$go = true;
}
if($element==$end){
$go = false;
}
}
$total_elems_new = count($new_array);
unset($new_array[$total_elems_new-1]);
print_r($new_array);
Testeed on PHP 5.6
Try:
$arr = array('3X' => '3X','EX'=> 'EX','VG'=>'VG','G'=>'G','F'=>'F','P'=>'P');
function findValuesBetweenTwoItems($arr, $start, $end) {
$result = [];
$has_started = false;
foreach ( $arr as $item->$value ) {
if( ( $item != $end && $has_started ) || $item == $start) {
array_push($result, $value);
$has_started = true;
}
if( $item == $end ) {
array_push($result, $value);
return $result;
}
}
$my_values = findValuesBetweenTwoItems($arr, 'EX', 'F');
var_dump($my_values);
Try this:
$array = array('3X' => '3X','EX'=> 'EX','VG'=>'VG','G'=>'G','F'=>'F','P'=>'P');
$arrayKeys = array_keys($array);
$input1 = '3X';
$input2 = 'F';
if(in_array($input1,$array) && in_array($input2,$array)) {
if (array_search($input1, array_keys($array)) >= 0) {
if (array_search($input2, array_keys($array)) >= 0) {
if (array_search($input1, array_keys($array)) < array_search($input2, array_keys($array))) {
echo "Keys in between: ";
for ($i = array_search($input1, array_keys($array)); $i <= array_search($input2, array_keys($array)); $i++) {
echo $array[$arrayKeys[$i]] . ", ";
}
} else {
echo "Keys in between: ";
for ($i = array_search($input2, array_keys($array)); $i <= array_search($input1, array_keys($array)); $i++) {
echo $array[$arrayKeys[$i]] . ", ";
}
}
} else {
echo "Value not found!";
}
} else {
echo "Value not found!";
}
} else{
echo "Value not found!";
}
$from = 'EX';
$to = 'F';
$result = null;
$state = 0;
foreach ($a as $k => $v) {
if (($state == 0 && $from === $v) || ($state == 1 && $to === $v))
$state++;
if ($state && $state < 3)
$result[$k] = $v;
elseif ($state >= 2)
break;
}
if ($state != 2)
$result = null;
The loop searches for the first occurrence of $from, if $state is 0 (initial value), or the first occurrence of $to, if $state is 1. For other values of $state, the loop stops processing.
When either $from, or $to is found, $state is incremented. The values are stored into $result while $state is either 1 ($from is found), or 2 ($to is found).
Thus, $state == 2 means that both values are found, and $result contains the values from the $a array between $from and $to. Otherwise, $result is assigned to null.

I need to ignore certain items of an array and create initials from remaining

I need to avoid the CN=Users, DC=aab, DC=local values that return from the array. Then save the INITIALS of the remaining names into a new array. Any help would be appreciated. I'm just not really sure where to start.
This is how it returns right now when I do the following.
$reportees = $_SESSION["user"]->directreports;
$reportees = implode(",", $reportees);
CN=John Doe,CN=Users,DC=aab,DC=local,CN=Jane Ann Doe,CN=Users,DC=aab,DC=local
$reportees = $_SESSION["user"]->directreports;
$blacklist = array('CN=Users', 'DC=aab', 'DC=local');
$arrayOfInitials = array();
foreach($reportees as $key=>$reportee){
// ignore the unwanted values :
if(!in_array($reportee, $blacklist)){
// take only the value after the "=":
$reportee = explode("=", $reportee);
if(isset($reportee[1])){
$reportee = $reportee[1];
$reporteeNames = explode(" ", $reportee);
$initials = "";
// get the initials :
foreach($reporteeNames as $name){
$initials .= strtoupper($name[0]);
}
$arrayOfInitials[] = $initials;
}
}
}
$initialsAsStr = implode(',', $arrayOfInitials);
var_dump($initialsAsStr);
The output will be :
string(10) "JD,B,JAD,B"
<?php
$in = ['CN=John Doe','CN=Users','DC=aab','DC=local','CN=Jane Ann Doe','CN=Users','DC=aab','DC=local'];
function initials_from_value($i) {
strtok($i, '=');
$i = strtok('=');
$names = explode(' ', $i);
$initials = array_map(function ($i) { return substr($i, 0, 1); }, $names);
return $initials;
}
$out = array();
foreach($in as $item) {
if(strpos($item, 'CN=') === 0 && $item !== 'CN=Users') {
$out[] = implode(' ', initials_from_value($item));
}
}
var_export($out);
Output:
array (
0 => 'J D',
1 => 'J A D',
)
Addendum (Collate only first and last initials):
$out = array();
foreach($in as $item) {
if(strpos($item, 'CN=') === 0 && $item !== 'CN=Users') {
if( ($initials = initials_from_value($item)) && count($initials) >= 2) {
$first = reset($initials);
$last = end($initials);
$out[] = $first . $last;
}
}
}
var_export($out);
Output:
array (
0 => 'JD',
1 => 'JD',
)
The following should work (PHP >= 5.4):
$reportees = array('CN=John Doe',
'CN=Users',
'DC=aab',
'DC=local',
'CN=Jane Ann Doe',
'CN=Users',
'DC=aab',
'DC=local');
$result = [];
foreach ($reportees as $value) {
switch ($value) {
// ignore these values
case 'CN=Users':
case 'DC=aab':
case 'DC=local':
continue 2;
// get initials of these values
default:
$expr = '/(?<=\s|^)[a-z]/i';
preg_match_all($expr, explode('=', $value)[1], $matches);
$result[] = strtoupper(implode('', $matches[0]));
}
}
$reportees = implode(',', $result);
Result:
JD,JAD
You can filter the array with a closure, and have it return FALSE for unwanted items, so that it can be filtered with array_filter.
This way you can check the results incrementally, which I find easier to debug.
$values = array_map(
/* Get a reportee, return the name or FALSE */
function($reportee) {
list($key, $value) = explode('=', $reportee);
switch ($key) {
case 'CN': // CN=Users or CN=Jane Ann Doe
if ('Users' === $value) {
return false;
}
// $value is now hopefully Jane Ann Doe.
return $value;
default: // Anything else gets FALSEd.
return false;
}
},
$reportees
);
// Eliminate unwanted results:
// [ 0 => false, 1 => false, 2 => false, 3 => 'Jane Ann Doe', 4 => false ]
$values = array_filter($values);
// $values should now be something like [ 3 => 'Jane Ann Doe' ]
// Get initials.
$values = array_map(
/* input: "Jane Ann Doe"; output: "JAD" */
function ($value) {
$words = preg_split('#\\s+#', $value);
$initials = array_map(
function ($word) {
return substr($word, 0, 1);
},
$words
);
return implode('', $initials);
},
$values
);
// $values is now [ '3' => 'JAD' ].
// You can use array_values($values) to renumber the array.

PHP combine arrays on similar elements

I have some data in this format:
even--heaped<br />
even--trees<br />
hardrocks-cocked<br />
pebble-temple<br />
heaped-feast<br />
trees-feast<br />
and I want to end up with an output so that all lines with the same words get added to each other with no repeats.
even--heaped--trees--feast<br />
hardrocks--cocked<br />
pebbles-temple<br />
i tried a loop going through both arrays but its not the exact result I want. for an array $thing:
Array ( [0] => even--heaped [1] => even--trees [2] => hardrocks--cocked [3] => pebbles--temple [4] => heaped--feast [5] => trees--feast )
for ($i=0;$i<count($thing);$i++){
for ($j=$i+1;$j<count($thing);$j++){
$first = explode("--",$thing[$i]);
$second = explode("--",$thing[$j]);
$merge = array_merge($first,$second);
$unique = array_unique($merge);
if (count($unique)==3){
$fix = implode("--",$unique);
$out[$i] = $thing[$i]."--".$thing[$j];
}
}
}
print_r($out);
but the result is:
Array ( [0] => even--heaped--heaped--feast [1] => even--trees--trees--feast [4] => heaped--feast--trees--feast )
which is not what i want. Any suggestions (sorry about the terrible variable names).
This might help you:
$in = array(
"even--heaped",
"even--trees",
"hardrocks--cocked",
"pebbles--temple",
"heaped--feast",
"trees--feast"
);
$clusters = array();
foreach( $in as $item ) {
$words = explode("--", $item);
// check if there exists a word in an existing cluster...
$check = false;
foreach($clusters as $k => $cluster) {
foreach($words as $word) {
if( in_array($word, $cluster) ) {
// add the words to this cluster
$clusters[$k] = array_unique( array_merge($cluster, $words) );
$check = true;
break;
}
}
}
if( !$check ) {
// create a new cluster
$clusters[] = $words;
}
}
// merge back
$out = array();
foreach( $clusters as $cluster ) {
$out[] = implode("--", $cluster);
}
pr($out);
Try this code:
<?php
$data = array ("1--2", "3--1", "4--5", "2--6");
$n = count($data);
$elements = array();
for ($i = 0; $i < $n; ++$i)
{
$split = explode("--", $data[$i]);
$word_num = NULL;
foreach($split as $word_key => $word)
{
foreach($elements as $key => $element)
{
if(isset($element[$word]))
{
$word_num = $key;
unset($split[$word_key]);
}
}
}
if(is_null($word_num))
{
$elements[] = array();
$word_num = count($elements) - 1;
}
foreach($split as $word_key => $word)
{
$elements[$word_num][$word] = 1;
}
}
//combine $elements into words
foreach($elements as $key => $value)
{
$words = array_keys($value);
$elements[$key] = implode("--", $words);
}
var_dump($elements);
It uses $elements as an array of hashes to store the individual unique words as keys. Then combines the keys to create appropriate words.
Prints this:
array(2) {
[0]=>
string(10) "1--2--3--6"
[1]=>
string(4) "4--5"
}
Here is a solution with a simple control flow.
<?php
$things = array('even--heaped', 'even--trees', 'hardrocks--cocked',
'pebble--temple', 'heaped--feast' ,'trees--feast');
foreach($things as $thing) {
$str = explode('--', $thing);
$first = $str[0];
$second = $str[1];
$i = '0';
while(true) {
if(!isset($a[$i])) {
$a[$i] = array();
array_push($a[$i], $first);
array_push($a[$i], $second);
break;
} else if(in_array($first, $a[$i]) && !in_array($second, $a[$i])) {
array_push($a[$i], $second);
break;
} else if(!in_array($first, $a[$i]) && in_array($second, $a[$i])) {
array_push($a[$i], $first);
break;
} else if(in_array($first, $a[$i]) && in_array($second, $a[$i])) {
break;
}
$i++;
}
}
print_r($a);
?>
It seems you have already selected user4035's answer as best.
But i feel this one is optimized(Please correct me if i am wrong): eval.in
Code:
$array = Array ( 'even--heaped' , 'even--trees' ,'hardrocks--cocked' , 'pebbles--temple' , 'heaped--feast' , 'trees--feast' );
print "Input: ";
print_r($array);
for($j=0;$j < count($array);$j++){
$len = count($array);
for($i=$j+1;$i < $len;$i++){
$tmp_array = explode("--", $array[$i]);
$pos1 = strpos($array[$j], $tmp_array[0]);
$pos2 = strpos($array[$j], $tmp_array[1]);
if (!($pos1 === false) && $pos2 === false){
$array[$j] = $array[$j] . '--'.$tmp_array[1];unset($array[$i]);
}elseif(!($pos2 === false) && $pos1 === false){
$array[$j] = $array[$j] . '--'.$tmp_array[0];unset($array[$i]);
}elseif(!($pos2 === false) && !($pos1 === false)){
unset($array[$i]);
}
}
$array = array_values($array);
}
print "\nOutput: ";
print_r($array);

Categories