Array with empty values need to be discarded - php
Given, In a input form user can separate some specific names by new line and i am saving those names in an array. Then I print those names and at last say something like "thank you for the names".
$var = "name1
name2
";
$your_array = explode("\n", $var);
for($i=0; $i<(sizeof($your_array));$i++) {
echo ($your_array[$i]);
}
echo "Thank you for the names"
But the problem is if someone enter more than one newline before or after a name then the next name show after some distance like below
name1
name2
Thank you for the names
How can escape this and output as below
name1
name2
Thank you for the names
I tried to use array_filter() but it don't work here.
Update:
If someone input
$var = "name1\nname2\n\n\n
name3
name4";
output should be like
name1
name2
name3
name4
But all the answers show like
name1
name2
name3
name4
Let's use a foreach loop for the sake of simplicity...
1) We need to iterate through the new array and trim the names so we lose all whitespace.
2) We echo out the name, if and only if the length of the name is 1 or more.
3) We add on a <br> tag to make each name appear on a new line.
<?php
$var = "name1\nname2\n\n\n";
$your_array = explode("\n", $var);
foreach($your_array as $name)
{
if(preg_match("/[a-zA-Z0-9]{1,}/i", $name)) {
$name = trim($name);
echo (strlen($name) > 1) ? sprintf('%s<br>', $name) : '';
}
}
echo "Thank you for the names";
?>
$your_array = explode(PHP_EOL, $var);
$names = array();
for ($i = 0; $i < count($your_array); $i ++ )
{
// trim clean spaces and newlines surrounding each line
// resulting value is assigned to $test
// if this value is not empty the conditional is a true proposition
// so is assigned to $names
if ($test = trim($your_array[$i]))
$names[] = $test;
}
echo implode(PHP_EOL, $names) . PHP_EOL;
echo 'Thank you for the names.';
EDIT: using foreach
$your_array = explode(PHP_EOL, $var);
foreach ($your_array as $name)
{
if ($test = trim($name))
$names[] = $test;
}
if ($names)
{
// echo implode(PHP_EOL, $names) . PHP_EOL;
echo implode('<br />', $names) . '<br />';
echo 'Thank you for the names.';
}
else
echo 'Names missing.';
EDIT 2
trim accept a charlist to explicit removes, so if you want maintain spaces, make a list with newlines and carriage return only.
trim($name, "\r\n");
NOTE: PHP_EOL is the correct new line char depending of server (unix or windows).
Be a better PHP developer and use native PHP array functions:
$raw_arr = array(' trim ', 'fine', ' ');
array_walk($raw_arr, function(&$value) {
$value = trim($value);
});
$reduced_arr = array_filter($raw_arr);
print_r($reduced_arr);
Note: I have used a closure. If you are running PHP < 5.3, you'll need to move this to a UDF.
UPDATE
Seems like you don't wish to trim the user input. As such, you can drop array_walk and its closure.
$raw_arr = array(' trim ', 'fine', '');
$reduced_arr = array_filter($raw_arr);
print_r($reduced_arr);
for($i=0; $i<(sizeof($your_array));$i++) {
if (empty($your_array[$i])) continue;
echo ($your_array[$i]);
}
echo "Thank you for the names"
You can use array_filter + array_map + trim to discard empty space
$var = "name1
name2
";
$array = array_filter(array_map("trim",explode("\n", $var)));
echo implode(PHP_EOL, $array) , PHP_EOL;
echo "Thank you for the names";
Or just use preg_match_all
preg_match_all("/\S?([a-z0-9]+)\S?/", $var,$array);
echo implode(PHP_EOL, $array[0]),PHP_EOL;
echo "Thank you for the names";
Both Would Output
name1
name2
Thank you for the names
Related
PHP New Line after n commas
I want to insert a new line after n commas. For example I got this value: 385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426 How I could echo them all, but every 5th comma there should be a linebreak? 385,386,387,388,389, 390,391,392,393,394, 395,396,397,398,399, 400,401,402,403,404, 405,406,407,408,409, 410,411,412,413,414, 415,416,417,418,419, 420,421,422,423,424, 425,426
Here's one method: // Get all numbers $numbers = explode(',', $str); // Split into groups of 5 (n) $lines = array_chunk($numbers, 5); // Format each line as comma delimited $formattedLines = array_map(function ($row) { return implode(',', $row); }, $lines); // Format groups into new lines with commas at the end of each line (except the last) $output = implode(",\n", $formattedLines);
Try this <?php //Start //Add this code if your values in string like that $string = "385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426"; $string_array = explode(',', $string); //End //Add this code if your values in string like that //If you have values in array then direct use below code skip above code and replace $string_array variable with yours end($string_array); $last = key($string_array); foreach ($string_array as $key => $value) { if($last==$key){ echo $value; }else{ echo $value.','; } if(($key+1)%5==0){ echo "<br />"; } } ?>
Try like this. You can explode the string with commas and check for every 5th position there should be a line break. You can check it with dividing key with 5.(i.e) it will give you a remainder of 0 Please note that key starts from 0, so I have added (key+1), to make it start from 1 $string = "385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426"; $stringexplode = explode(",", $string); $countstringexplode = count($stringexplode); foreach($stringexplode as $key => $val) { $keyIncrement = $key+1; echo $val.($countstringexplode == $keyIncrement ? "" : ",") ; if(($keyIncrement) % 5 == 0) echo "<br>"; } ?>
In_array not working - compare two files
The code below is a simple version of what I am trying to do. The code will read in two files, see if there is a matching entry and, if there is, display the difference in the numbers for that item. But it isn't working. The first echo displays the word but the second echo is never reached. Would someone please explain what I am missing? $mainArry = array('Albert,8'); $arry = array('Albert,12'); foreach ($arry as $line) { $kword = explode(',', $line); echo 'kword '.$kword[0]; if (in_array($kword[0], $mainArry)) { echo 'line '.$line. ' has count of '.$kword[1] . '<br>'; } }
Your $mainArry contains a single element: the string 'Albert,8'. It looks like you want to use it as an array (elements 'Albert' and '8') instead of a string. You mention the code will read from two files, so you can 'explode' it to a real array, as you do with $arry. A simpler approach would be using str_getcsv() to parse the CSV string into $mainArry. $inputString = 'Albert,8'; $mainArry = str_getcsv($inputString); // now $mainArry is ['Albert','8'] $arry = array('Albert,12'); foreach ($arry as $line) { $kword = explode(',', $line); echo 'kword '.$kword[0]; if (in_array($kword[0], $mainArry)) { echo 'line '.$line. ' has count of '.$kword[1] . '<br>'; } } Test it here.
You are attempting to compare the string Albert with Albert,8, so they won't match. If you want to check if the string contains the keyword, assuming your array has more than one element, you could use: $mainArry = array('Albert,8'); $arry = array('Albert,12'); foreach ($arry as $line) { $kword = explode(',', $line); echo 'kword '.$kword[0]; foreach ($mainArry as $comp) { if (strstr($comp, $kword[0])) { echo 'line '.$line. ' has count of '.$kword[1] . '<br>'; } } } example: https://eval.in/728566
I don't recommend your way of working, but this is a solution, basically the process you apply to the $arry should also apply to the $mainArry you're trying to compare it to. $mainArry = array('Albert,8'); $arry = array('Albert,12'); /*** NEW function below takes the valus out of the main array. and sets them in their own array so they can be properly compared. ***/ foreach ($mainArry as $arrr){ $ma = explode(",",$arrr); $names[] = $ma[0]; $values[] = $ma[1]; } unset($arrr,$ma); foreach ($arry as $line) { $kword = explode(',', $line); echo 'kword '.$kword[0]; /// note var reference here is updated. if (in_array($kword[0], $names)) { echo '<br>line '.$kword[0]. ' has count of '.$kword[1] . '<br>'; } } Yeah, MarcM's answer above does the same thing in a neat single line, but I wanted to illustrate a little more under the hood operations of the value setting. :-/
PHP extract 1 or more value from array_filter
Sorry this must me simple but I am terrible on arrays. I need to extract $d1,$d2,$d3,$d4,$d5,$d6 from array_filter($d1,$d2,$d3,$d4,$d5,$d6) Example $pieces = array_filter([$d1,$d2,$d3,$d4,$d5,$d6]); if(count(array_filter($pieces)) == 2){ echo $d1.' '.$d2 } Thank you!
You need the array in a variable: (not sure on your context but is 'array_filter' needed at all? $myArray = array($d1, $d2, $d3, $d4, $d5, $d6); Then when echoing $d1.' '.$d2 for example: echo $myArray[0] . ' ' . $myArray[1]; Update So to more accurately answer your question, I'm assuming you want to echo all array items, use a for loop: $output; for ($i = 0; $i< count($pieces); $i++){ output .= $pieces[$i] . ' '; } echo $output;
you are on right track. Try below soltuion: $array = array('test1','test2','','test4','','','','testx'); //remove empty values $filterd_array = array_filter($array); //implode with space and print echo implode(' ', $filterd_array); output: test1 test2 test4 testx
Extract Words From Text That Have More Than 4 Charecters and Are A-Z
Hello I got this code from this this website and it works fine but want to be able to only show words with 4 charecters or more and A-Z no numbers. Any help would be very much appreciated thanks! $myvalue = "no no2 yess"; $arr = explode(' ',trim($myvalue)); echo $arr[0];
$myvalue = "no no2 yess"; $arr = explode(' ',trim($myvalue)); Explode is cutting your string by delimeter ( ' ' ), and putting content into and array ( $arr ). echo $arr[0]; // outputs 'no' echo $arr[1]; // outputs 'no2' echo $arr[2]; // outputs 'yess' foreach($arr as $value){ // loop throught each element //test if element is longer or equal to 4 and have only a-z A-Z. if(strlen($value) >=4 & preg_match('/^[a-zA-Z]{4,}$/', $value)){ //return the matching words echo $value; } } Here you can putt them again into the array like $newArray[] = $value instead of echo $value, and throw them out with loop anywhere.
how to order in while loop?
I want to get the count of characters from the following words in the string. For example, if my input is I am John then the output must be like this: 9 // count of 'I am John' 4 // count of 'I am' 1 // count of 'I' I use the code like this in PHP for this process: $string = 'I am John'; $words = explode(' ',$string); $count_words = count($words); $i =0; while ($i<$count_words){ if($i==0) { $words_length[$i] = strlen($words[$i]); } else { $words_length[$i] = strlen($words[$i])+1+$words_length[$i-1]; } echo $words_length[$i]."<br>"; $i++; } But it return the output like this: 1 4 9 Why ? Where is my error ? How can I change the ordering ? What does my code must be like ? Thanks in advance!
If you simply want to have the output in reverse order use array_reverse: print_r(array_reverse($words_length));
Your problem is that you're looping through the words left to right. You can't output the full length right to left, because each one depends on the words to it's left. You could take the echo out of the loop, and print the values after all have been calculated. $string = 'I am John'; $words = explode(' ',$string); $count_words = count($words); $i =0; while ($i<$count_words){ if($i==0) { $words_length[$i] = strlen($words[$i]); } else { $words_length[$i] = strlen($words[$i])+1+$words_length[$i-1]; } $i++; } print implode('<br />', array_reverse($words_length));
The quickest fix is to add print_r(array_reverse($words_length)); after the loop
You may use foreach and array_reverse to get the array values: foreach(array_reverse($words_length) as $val){ echo $val; }