This question already has answers here:
Fastest way of deleting a value in a comma separated list
(4 answers)
Closed 2 years ago.
I am storing numbers in a database with a string like 5,55,15,17,2,35
I want to remove say number 5 from the string, keeping the comma seperation set like it is.
The problem with using str_replace() is that all of the 5's will be removed. If i use str_replace('5,'', $string) thats fine, but the comma wouldn't be after the 5 if it was in the middle of the string or at the end. That same str_replace would also remove part of 15, and 55,
Am i missing something?
$array = explode(',', $string);
foreach ($array as $k => $v)
if ($v == 5) unset($array[$k]);
$string = implode(',', $array);
You probably shouldn't be storing a comma separated list of values in a single database column in the first place. It looks like a one-to-many association, which should be modeled with a separate table.
Split the string first by comma so you can work with the numbers directly. Remove 5 from the array, then recombine the array into a comma-delimited string.
Here's an example:
<?php
$input = '5,55,15,17,2,35';
echo "Input: $input<br />";
// Split the string by "exploding" the string on the delimiter character
$nums = explode(',', $input);
// Remove items by comparing to an array containing unwanted elements
$nums = array_diff($nums, array(5));
// Combine the array back into a comma-delimited string
$output = implode(',', $nums);
echo "Output: $output<br />";
// Outputs:
// Input: 5,55,15,17,2,35
// Output: 55,15,17,2,35
?>
str_replace([$num.",",",".$num],"",$input);
U can try something like this:
// Convert string into array of numbers
$arrOfNumbers = explode(',', $string);
// Find id of number for del
$numberForDelId = array_search($numberForDel, $arrOfNumbers);
//Delete number
unset($arrOfNumbers[$numberForDelId]);
// Convert back to string
$resultString = implode(',' $arrOfNumbers)
You should:
get the string
then "explode" the values into an array
and re-create the string without the number you want to remove.
Related
i am making php array count value function i am taking values from file get content and using it in it and want to count values but due to space its not working properly Here is my codes
$data = file_get_contents('testr.txt');
preg_match_all('#mob:-(\S+)-#',$data,$matches);
$nu=$matches[1];
$n=implode($nu,',');
$n="9024453561,9024453561,9024453561,9024453561,9024453561 ";
//in value of $n i am getting spce at end so array_count _value not working
$array = array($n);
$counts = array_count_values($array);
echo $counts['9024453561'];
Using array_map(), map over your data where your call implode like so:
$n=array_map('trim', implode($nu,','));
This will remove any white space you have in your array values.
Hope that helps,
You do not split the string into an array by array($n). Instead you get a single element containing the entire string including commas. Use trim and preg_split to get an array of values.
$n="9024453561,9024453561,9024453561,9024453561,9024453561 ";
$array = preg_split('~\\s*,\\s*~u', trim($n));
$counts = array_count_values($array);
echo $counts['9024453561'];
This also splits a string like " 123 , 456 , 789 ". \s* means zero or more whitespaces. The double slash is to escape the slash in the string literal. trim removes spaces from the begin and the end of the entire string.
There is no need to go through the implode at all, just call array_count_values on your preg_match_all result:
$data = file_get_contents('testr.txt');
preg_match_all('#mob:-(\S+)-#',$data,$matches);
$nu=$matches[1];
$counts = array_count_values($nu);
echo $counts['9024453561'];
This question already has answers here:
Explode string into array with no empty elements?
(12 answers)
Closed 2 years ago.
I want explode to return an empty array if the delimiter is not found.
Currently, I do something like this to get the explode behavior I want:
if (strpos($line, ' ') === false) {
$entries = [];
} else {
$entries = explode(' ', $line);
}
There must be a more concise way of getting this behavior without having to use preg_split. preg_split has its own behavior that is also undesirable, such as including the delimiter in the resultant array entries.
So, you have a string of space delimited data, e.g. 'foo bar'? Your rule is if there's no delimiter, meaning if the string is either a single value ('foo') or an empty string (''), then you want an empty array; otherwise you want the split delimited data?
$entries = explode(' ', $line);
if (count($entries) < 2) {
$entries = [];
}
There isn't really a sane way to make this specific condition shorter, but this removes the redundant inspection of the string and clearly states what the code is trying to do.
This question already has answers here:
Check if String has only Integers separated by comma in PHP
(3 answers)
Closed 6 years ago.
How to check that php explode hold only comma separated integer values.
for example i have a
$str= '10,20,30,40,50,60,70,80,90,100';
$arr = explode(',',$str);
and i want to check if the value in $str is 10,20,30 and so on. and cannot contain any of string and words.
I basically populate a drop-down from this $arr and i want to make check if user enter integer values with comma then its show the dropdown else if user enter any other format.
i also use is_int or is_numeric but it cannot solve my problem.
thanks for advance .
What you're looking for is ctype_digit
$str= '10,20,30,40,50,60,70,80,90,100';
$arr = explode(',',$str);
foreach($arr as $a){
if(!ctype_digit($a)){
//Not an int
}else{
//is an int
}
}
Output:- https://eval.in/734431
Reference:- http://php.net/ctype_digit
I have a text box.
I am enter the value in text box like 12 13 14.
and i am want to convert this into 12,13,14 and then convert it into array and show each separate value.
If your form field asks for the values without a comma, then you will need to explode the POST data by space. What you're doing now is imploding it by comma (you can't implode a string to begin with), and then trying to pass that into a foreach loop. However, a foreach loop will only accept an array.
$ar = explode(' ',$da);
That simple change should fix it for you. You will want to get rid of the peculiar die() after your foreach (invalid syntax, and unclear what you're trying to do there!), and validate your data before the loop instead. By default, if you explode a string and no matching delimiters are found, the result will be an array with a single key, which you can pass into a loop without a problem.
Are you sure you want to expect the user enters data in that particular format? I mean, what if the user uses more than one space character, or separate the numbers actually with commas? or with semicolons? or enters letters instead of numbers? Anyway.. at least you could transform all the spaces to a single space character and then do the explode() as suggested:
$da = trim(preg_replace('/\s+/', ' ', $_POST['imp']));
$ar = explode(' ', $da);
before your foreach().
use explode instead of implode as
The explode() function breaks a string into an array.
The implode() function returns a string from the elements of an array.
and you cannot do foreach operation for a string.
$da=$_POST['imp'];
$ar = explode(' ',$da);
foreach($ar as $k)
{
$q="insert into pb_100_fp (draw_3_fp) values ('".mysqli_real_escape_string($conn, $k)."')";
$rs=mysqli_query($conn, $q);
echo $k.",";
}
then you will get this output
o/p : 12,13,14,
I have made a system with browsing files; Now I have a problem:
My path string like this: A/Abba/2004/
I want to remove the text between the last 2 slashes (which is 2004 in this case).
So the output should look like A/Abba/
Can anyone help me as how to archive this in php?
Thanks.
If you try to remove last part of string you can do this this way:
$input = 'A/Abba/2014/';
$array = array_filter(explode('/', $input));
array_pop($array);
$correct = implode('/', $array);
array_filter removes empty strings from array
explode converts string to array by given delimiter
array_pop remove last item from given array
implode converts array to string using given 'glue'