Remove Blank Items in Array PHP [duplicate] - php

This question already has answers here:
Remove empty array elements
(27 answers)
Closed 6 years ago.
I have a textarea box that takes barcodes separated by a new line. When they are processed, the new lines become commas. But if somebody inputs:
123456
234567
...
with a bunch of spaces under each code as such, it then becomes
$barcode_list = 123456,,,234567
I am able to strip the commas from the end, and I have tried:
$array = explode(",", $barcode_list);
foreach($array as $item){ //Separate each item
if ($item == "") {
unset($item);
}
but it doens't seem to work, I still get mysqli errors etc. Is there any way to get around this?

You should first remove unnecessary commas, then explode. Fewer steps...
// every sequence of commas becomes one comma
$barcode_list=preg_replace("/,+/",",",$barcode_list);
// explode the string into an array
$array = explode(",", $barcode_list);

You're doing an unset that doesn't really affect your array.
Do this:
$array = explode(",", $barcode_list);
foreach($array as $key => $item){ //Separate each item
if ($item == "") {
unset($array[$key]);
}
}

Related

Better way to convert string with multiple spaces into array [duplicate]

This question already has answers here:
How can I explode a string by more than one space, but not by exactly one space in php
(2 answers)
Closed 8 months ago.
I am reading from files and each line has multiple spaces. Example:
$line = 'Testing Area 1 10x10';
I need to convert it into array with 3 elements only so I can save it to a table. Final output should be like this:
$final_array = array('Testing Area', '1', '10x10');
This is how I'm doing it so far:
// read by line
foreach(explode(PHP_EOL, $contents) as $line) {
// split line by 2 spaces coz distance between `1` and `10x10` is atleast 2 spaces
$arr = explode(' ', $line);
// But because `Testing Area` and `1` has so many spaces between them,
// exploding the $line results to empty elements.
// So I need to create another array for the final output.
$final_array = array();
// loop through $arr to check if value is empty
// if not empty, push to $final array
foreach ($arr as $value) {
if (!empty($value)) {
array_push($final_array, $value);
}
}
// insert into table the elements of $final_array according to its column
}
Is there a better way to do this instead of looping through the array and checking each element if it's empty?
Take note that I have multiple files to read, each containing atleast 200 lines like that.
Use preg_split(), with 2 or more spaces as the delimiter.
$array = preg_split('/\s{2,}/', $line);
Assuming the criteria for splitting be two or more spaces, we can try using preg_split here:
$line = 'Testing Area 1 10x10';
$final_array = preg_split("/\s{2,}/", $line);
print_r($final_array);
This prints:
Array
(
[0] => Testing Area
[1] => 1
[2] => 10x10
)

PHP object property string concatenation in foreach without setting empty string first [duplicate]

This question already has answers here:
Create a comma-separated string from a single column of an array of objects
(15 answers)
Closed 7 months ago.
I have some WordPress custom fields data that I am looping through and creating a comma separated string. The (small) issue is that I get a warning if I don't set the property as empty / null etc before looping.
I guess you can't concatenate a string if it doesn't yet exist. Although I get the warning, the foreach does what I need an there are no errors.
To stop the warning I have set the property as an empty string to start:
$memlog->postnominals = "";
foreach (get_field('post_nominals', $post->id) as $postnominal) {
$memlog->postnominals .= $postnominal->post_title . ", ";
}
Although not a big issue, I would rather know if there is a way I can do this without setting an empty string?
Don't use concatenation to begin with, join an array, that way you also don't have to strip off the last , afterwards:
$memlog->postnominals = join(', ', array_column(get_field(...), 'post_title'));
array_column only works with objects in PHP 7+, for older versions use a map:
$memlog->postnominals = join(', ', array_map(
function ($p) { return $p->post_title; },
get_field(...)
));
Please use array then implode that data from array to form comma separated string.
Example:
$aa = array(1 => 'a', 2 => 'b', 3 => 'c');
foreach ($aa as $k => $v) {
$b[] = $v;
}
print_r(implode(',', $b));

Implode() vs Foreach() [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Have those syntaxes:
Foreach:
$array=array('v1','v2','v3');
foreach( $array as $value ){
echo $value;
}
Output:
v1v2v3
Implode:
$array=array('v1','v2','v3');
$value=implode(" ",$array);
echo $value;
Output:
v1 v2 v3
I need some help understanding the difference between implode(),foreach() used in the situation above.Are they the same? Or what is the difference? Which i should use and when?
For the record,i know small differences,and things like that.I just want to know your opinion and if there is something i didn't know about those functions.
Generally loops may be used for making any action you want.
You can for example concatenate string with other string depending or array element:
$array=array('v1','v2','v3');
foreach ($array as $value) {
if ($value == 'v1') {
echo $value.' something';
}
else {
echo $value.' something2';
}
}
and if you have numbers in your array you can do math operations:
$array=array(1,2,3);
foreach ($array as $value) {
echo ($value + 5).' ';
}
You can also change array elements:
$array=array(1,2,3);
foreach ($array as &$value) {
$value += 3;
}
unset($value);
foreach ($array as $value ){
echo $value.' ';
}
// result: 4 5 6
Implode is just a function that merge array elements and put a splitter between them. Nothing more. It doesn't change array elements. It simple returns output string. It's usually used for preparing data to display.
Also implode is much more convenient for putting splitter between elements. In loop if you want to put space between all elements but you don't need to put space after last element you need to make extra checks for last element and using implode you don't need to care because implode just does it for you.
And in your case, output wouldn't be the same because your loop would output:
v1v2v3 and implode would output v1 v2 v3 because you used space separator
foreach is a loop statement. implode is a function. That's the difference. You are supposed to use foreach for any kind of operation for each element in an array. But implode is a helper method that binds the elements of the given array by using the given string as binder.
foreach() : it's a looping concept means you get values one by one and print you will found each result/value seperate while you not concat that.
implode() : convert an array to string with passsing glue. and you will get all array values in one string.
implode() also iterating array internally, and converting array into string
loop is also doing same thing here,
loop advantage here
1) when you want to conditional part, for instance
you want to exclude v2 from string or other operation depend on requirement
$array=array(1,2,3);
foreach ($array as $value ){
if($value == 2) continue;
echo $value." ";
}
these things can't apply in implode function
2) In loop you can direct buffer output or append into string.. [this is denpend on requirement],
import is only function that is combine array values into string.
how can it be same, both r used in different places. for example
list($y,$m,$d)=explode("-",$query); //separating and storing in variable `y-m-d`
$arr=array($m,$d);
$cat=implode('-',$arr); //u got that format again with only two variables
implode expects array.
where foreach is a loop which iterates through given array() until and unless it meets the false condition and gets out of the loop

Ignore first value in an array [duplicate]

This question already has answers here:
Get and remove first element of an array in PHP
(2 answers)
Closed 8 years ago.
I have a range of fourier transform values in php as shown below.
[8974,398.22605659378,340.40931712583,224.61805748557,224.21476160103,531.02102311671,348.09311299013,74.373164045484,440.15451832283,379.54095616825,801.05398080895,184.15175862698,539.59590498835,114.82864261836,595.84662567888,488.12623039438,370,488.12623039438,595.84662567888,114.82864261836,539.59590498835,184.15175862698,801.05398080895,379.54095616825,440.15451832283,74.373164045484,348.09311299013,531.02102311671,224.21476160103,224.61805748557,340.40931712582,398.22605659378]
How do I actually ignore/delete away the first value in this case "8974" in php language?
You can use array_shift();
Like
$array=array(8974,398.22605659378,340.40931712583,224.61805748557,224.21476160103,531.02102311671,348.09311299013,74.373164045484,440.15451832283,379.54095616825,801.05398080895,184.15175862698,539.59590498835,114.82864261836,595.84662567888,488.12623039438,370,488.12623039438,595.84662567888,114.82864261836,539.59590498835,184.15175862698,801.05398080895,379.54095616825,440.15451832283,74.373164045484,348.09311299013,531.02102311671,224.21476160103,224.61805748557,340.40931712582,398.22605659378);
array_shift($array);
print_r($array);
You could use array_shift
ie:
$myArray = array(8974,398.22605659378,340.40931712583,224.61805748557,224.21476160103,531.02102311671,348.09311299013,74.373164045484,440.15451832283,379.54095616825,801.05398080895,184.15175862698,539.59590498835,114.82864261836,595.84662567888,488.12623039438,370,488.12623039438,595.84662567888,114.82864261836,539.59590498835,184.15175862698,801.05398080895,379.54095616825,440.15451832283,74.373164045484,348.09311299013,531.02102311671,224.21476160103,224.61805748557,340.40931712582,398.22605659378);
array_shift($myArray)
You can easily unset first element to Delete it:
unset($array[0]);
Ignore it
Create a temporary array from the first by skipping the first element:
foreach (array_slice($arr, 1) as $xyz) {
/// ...
}
Or, without creating a temporary array:
reset($arr); next($arr); // reset and skip first element
while (list($key, $value) = each($arr)) {
echo $value;
}
Modify it
Modify the array in place by shifting the first item off:
array_shift($arr);
// do whatever you want

How do I loop through this hidden field format [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
How do i Loop through the hidden field items and put in Session using PHP
I have a hidden Field which contains this format which contains the Set of rows separated by ';'(semicolon)
and each row contains some columns name separated by ':' (colon) and each column value separated by ',' (comma)
so my format would be ENO:123,ENAME:XYZ,SAL:1200; ENO:598,ENAME:AIR,SAL:1300; which is what stored in hidden field
So How do i grab each column such as ENO ,ENAME and SAL their values for any number of rows written to hidden field
so i have my own custom session function where i can set the key and value .So on looping the values
I should be able to put MyCustomSessionFunction('ENAME',??????).How do i fill this .
I did not get Proper Replies Earlier .can anyone please help me
$hiddenformat = $_POST['hiddenfield'];
string(80) "ENO:1000,ENAME:B,SAL:10;ENO:1000,ENAME:S,SAL:100;"
when i vardump($hiddenformat) I am getting the above format .How do i explode and loop and assign each value to my
custom session function
foreach( $outer_array as $outer_key => $inner_array )
{
foreach( $inner_array as $key => $value )
{
}
}
$hiddenformat = $_POST['hiddenfield'];
$parts = explode(',', $hiddenformat);
foreach($parts as $part) {
$bits = explode(':', $part);
...
}
Given a $hiddenformat of ENO:1000,ENAME:B,SAL:..., the first explode will split the line at every comma, giving you a $parts array that looks like:
$parts = array(
0 => 'ENO:1000',
1 => 'ENAME:B',
2 => 'SAL:.....
);
Yuu use foreach to loop over this $parts array, and split the $part at every colon (:). So at each stage, $bits will look like:
$bits = array(
0 => 'ENO',
1 => '1000'
)
and then on the next iteration will
$bits = array(
0 => 'ENAME',
1 => 'B'
)
and so on. What you do with those individual chunks is up to you.
And yes, this was all present in the answers of the other questions. You just had to do a bit of work to put it all together.
Yeah, it was.
It's just to say that around that, you have to explode() by ";" and in the loop use Marc's code, since there are multiple Sets of data in the string

Categories