I have explode here is the result of var_dump:
and I want get the result from explode:
7 [remove other string]
0 [if contain "-"]
0 [if contain "-"]
0 [if contain "-"]
Here, I just used comma as delimiter:
var_dump (explode(",", $rowData[0][13]));
die();
Does anyone have the solution to solved this?
Thank You.
Use array_map() function and in it use filter_var() to sanitize number value.
Try
$rowData = ['JJ7', 'B-', 'S-', 'M-'];
$result = array_map(function($v) {
return abs((int) filter_var($v, FILTER_SANITIZE_NUMBER_INT));
}, $rowData );
var_dump( $result );
//output
// array(4) { [0]=> int(7) [1]=> int(0) [2]=> int(0) [3]=> int(0) }
<?php
$data_result = explode(",", $rowData[0][13])
for($data_count=0;$data_count<count($data_result);$data_count++)
{
if(substr($data_result[$data_count], -1) == '-')
{
echo $data_result[$data_count]
}
}
?>
Related
Is there any way besides for explode to convert a php string that looks like: "[2,0,[]]" into an array?
My array output should be like:
array(2,0,array())
And "[2,0,[1,2,3,4]]" this sting should be:
array(2,0,array(1,2,3,4))
I do not want to use explode because it just seems like to much code for a very simple task. in javascript it is a one liner:
JSON.parse('[2,0,[1,2,3,4]]');
Your input looks like a JSON string, which can be converted with json_decode() function :
json_decode("[2,0,[]]", true);
/*
Array (
0 => 2,
1 => 0,
2 =>
Array (
),
)
*/
As specified by Tareq Mahmood json_decode would work but in case you want to do it from scratch:
<?php
$string = "[2,0,[1,2,3,4,]]";
$i = 0;
$array = array();
$handlerCount = 0;
$arrayTmp = array();
$countArr2=0;
while(isset($string[$i])){
switch($string[$i]){
case ",":
break;
case "[":
$handlerCount++;
break;
case "]":
$handlerCount--;
break;
default:
if($handlerCount == 1){
$array[$i] = (int)$string[$i];
}else{
$arrayTmp[$countArr2] = (int)$string[$i];
$countArr2++;
}
}
$i++;
}
array_push($array,$arrayTmp);
var_dump($array);
?>
[Proof of concept]
array(3) {
[1]=>
int(2)
[3]=>
int(0)
[4]=>
array(4) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
}
}
Remove element from array if string contains any of the characters.For example Below is the actual array.
array(1390) {
[0]=>
string(9) "Rs.52.68""
[1]=>
string(20) ""php code generator""
[2]=>
string(9) ""Rs.1.29""
[3]=>
string(21) ""php codes for login""
[4]=>
string(10) ""Rs.70.23""
}
I need the array to remove all the elements which start with RS.
Expected Result
array(1390) {
[0]=>
string(20) ""php code generator""
[1]=>
string(21) ""php codes for login""
}
What i tried so far :
foreach($arr as $ll)
{
if (strpos($ll,'RS.') !== false) {
echo 'unwanted element';
}
From above code how can i remove unwanted elements from array .
You can get the $key in the foreach loop and use unset() on your array:
foreach ($arr as $key => $ll) {
if (strpos($ll,'RS.') !== false) {
unset($arr[$key]);
}
}
Note that this would remove none of your items as "RS" never appears. Only "Rs".
This sounds like a job for array_filter. It allows you to specify a callback function that can do any test you like. If the callback returns true, the value if returned in the resulting array. If it returns false, then the value is filtered out.
$arr = array_filter($arr,
function($item) {
return strpos($item, 'Rs.') === false;
});
Rs is different than RS you want to use stripos rather than strpos for non case sensitive checking
foreach($arr as $key => $ll)
{
if (stripos($ll,'RS.') !== false) {
unset($arr[$key]);
}
}
or use arrayfilter as pointed out
I have a string having 128 values in the form of :
1,4,5,6,0,0,1,0,0,5,6,...1,2,3.
I want to pair in the form of :
(1,4),(5,6),(7,8)
so that I can make a for loop for 64 data using PHP.
You can accomplish this in these steps:
Use explode() to turn the string into an array of numbers
Use array_chunk() to form groups of two
Use array_map() to turn each group into a string with brackets
Use join() to glue everything back together.
You can use this delicious one-liner, because everyone loves those:
echo join(',', array_map(function($chunk) {
return sprintf('(%d,%d)', $chunk[0], isset($chunk[1]) ? $chunk[1] : '0');
}, array_chunk(explode(',', $array), 2)));
Demo
If the last chunk is smaller than two items, it will use '0' as the second value.
<?php
$a = 'val1,val2,val3,val4';
function x($value)
{
$buffer = explode(',', $value);
$result = array();
while(count($buffer))
{ $result[] = array(array_shift($buffer), array_shift($buffer)); }
return $result;
}
$result = x($a);
var_dump($result);
?>
Shows:
array(2) { [0]=> array(2) { [0]=> string(4) "val1" [1]=> string(4) "val2" } [1]=> array(2) { [0]=> string(4) "val3" [1]=> string(4) "val4" } }
If modify it, then it might help you this way:
<?php
$a = '1,2,3,4';
function x($value)
{
$buffer = explode(',', $value);
$result = array();
while(count($buffer))
{ $result[] = sprintf('(%d,%d)', array_shift($buffer), array_shift($buffer)); }
return implode(',', $result);
}
$result = x($a);
var_dump($result);
?>
Which shows:
string(11) "(1,2),(3,4)"
How can I check in PHP whether a string contains '-'?
Example
ABC-cde::abcdef
if '-' is found
then I have to perform split() to split ABC from cde::abcdef
else
no need to perform split()
like cde::abcdef
if (strpos($string, "-") !== false)
{
split();
}
Just use explode that should be sufficient
eg. explode ('-',$urstring);
This will only split it (into an array of strings) if "-" exist else return the entire string as a array
How about just using the $limit parameter of explode()?
This will return an array in both your examples, with only one element in the latter case.
Note that split() is deprecated as of PHP 5.3: http://php.net/manual/en/function.split.php
$s1 = 'ABC-cde::abcdef';
$s2 = 'cde::abcdef';
$s3 = 'ABC-with-more-hyphens';
explode('-', $s1, 2);
// array(2) {
// [0]=>
// string(3) "ABC"
// [1]=>
// string(11) "cde::abcdef"
// }
explode('-', $s2, 2);
// array(1) {
// [0]=>
// string(11) "cde::abcdef"
// }
explode('-', $s3, 2);
// array(2) {
// [0]=>
// string(3) "ABC"
// [1]=>
// string(17) "with-more-hyphens"
// }
Just split() it and count the elements in the return array. Maybe it's even enough to continue with the first (or last) element, e.g. $newstring = split($oldstring, '-')[0]...
PHP's explode function returns an array of strings split on some provided substring. It will return empty strings when there are leading, trailing, or consecutive delimiters, like this:
var_dump(explode('/', '1/2//3/'));
array(5) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(0) ""
[3]=>
string(1) "3"
[4]=>
string(0) ""
}
Is there some different function or option or anything that would return everything except the empty strings?
var_dump(different_explode('/', '1/2//3/'));
array(3) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "3"
}
Try preg_split.
$exploded = preg_split('#/#', '1/2//3/', -1, PREG_SPLIT_NO_EMPTY);
array_filter will remove the blank fields, here is an example without the filter:
print_r(explode('/', '1/2//3/'))
prints:
Array
(
[0] => 1
[1] => 2
[2] =>
[3] => 3
[4] =>
)
With the filter:
php> print_r(array_filter(explode('/', '1/2//3/')))
Prints:
Array
(
[0] => 1
[1] => 2
[3] => 3
)
You'll get all values that resolve to "false" filtered out.
see http://uk.php.net/manual/en/function.array-filter.php
Just for variety:
array_diff(explode('/', '1/2//3/'), array(''))
This also works, but does mess up the array indexes unlike preg_split. Some people might like it better than having to declare a callback function to use array_filter.
function not_empty_string($s) {
return $s !== "";
}
array_filter(explode('/', '1/2//3/'), 'not_empty_string');
I have used this in TYPO3, look at the $onlyNonEmptyValues parameter:
function trimExplode($delim, $string, $onlyNonEmptyValues=0){
$temp = explode($delim,$string);
$newtemp=array();
while(list($key,$val)=each($temp)) {
if (!$onlyNonEmptyValues || strcmp("",trim($val))) {
$newtemp[]=trim($val);
}
}
reset($newtemp);
return $newtemp;
}
It doesn't mess up the indexes:
var_dump(trimExplode('/', '1/2//3/',1));
Result:
array(3) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "3"
}
Here is a solution that should output a newly indexed array.
$result = array_deflate( explode( $delim, $array) );
function array_deflate( $arr, $emptyval='' ){
$ret=[];
for($i=0,$L=count($arr); $i<$L; ++$i)
if($arr[$i] !== $emptyval) $ret[]=$arr[$i];
return $ret;
}
While fairly similar to some other suggestion, this implementation has the benefit of generic use. For arrays with non-string elements, provide a typed empty value as the second argument.
array_deflate( $objArray, new stdClass() );
array_deflate( $databaseArray, NULL );
array_deflate( $intArray, NULL );
array_deflate( $arrayArray, [] );
array_deflate( $assocArrayArray, [''=>NULL] );
array_deflate( $processedArray, new Exception('processing error') );
.
.
.
With an optional filter argument..
function array_deflate( $arr, $trigger='', $filter=NULL, $compare=NULL){
$ret=[];
if ($filter === NULL) $filter = function($el) { return $el; };
if ($compare === NULL) $compare = function($a,$b) { return $a===$b; };
for($i=0,$L=count($arr); $i<$L; ++$i)
if( !$compare(arr[$i],$trigger) ) $ret[]=$arr[$i];
else $filter($arr[$i]);
return $ret;
}
With usage..
function targetHandler($t){ /* .... */ }
array_deflate( $haystack, $needle, targetHandler );
Turning array_deflate into a way of processing choice elements and removing them from your array. Also nicer is to turn the if statement into a comparison function that is also passed as an argument in case you get fancy.
array_inflate being the reverse, would take an extra array as the first parameter which matches are pushed to while non-matches are filtered.
function array_inflate($dest,$src,$trigger='', $filter=NULL, $compare=NULL){
if ($filter === NULL) $filter = function($el) { return $el; };
if ($compare === NULL) $compare = function($a,$b) { return $a===$b; };
for($i=0,$L=count($src); $i<$L; ++$i)
if( $compare(src[$i],$trigger) ) $dest[]=$src[$i];
else $filter($src[$i]);
return $dest;
}
With usage..
$smartppl=[];
$smartppl=array_inflate( $smartppl,
$allppl,
(object)['intelligence'=>110],
cureStupid,
isSmart);
function isSmart($a,$threshold){
if( isset($a->intellgence) ) //has intelligence?
if( isset($threshold->intellgence) ) //has intelligence?
if( $a->intelligence >= $threshold->intelligence )
return true;
else return INVALID_THRESHOLD; //error
else return INVALID_TARGET; //error
return false;
}
function cureStupid($person){
$dangerous_chemical = selectNeurosteroid();
applyNeurosteroid($person, $dangerous_chemical);
if( isSmart($person,(object)['intelligence'=>110]) )
return $person;
else
lobotomize($person);
return $person;
}
Thus providing an ideal algorithm for the world's educational problems. Aaand I'll stop there before I tweak this into something else..
Write a wrapper function to strip them
function MyExplode($sep, $str)
{
$arr = explode($sep, $str);
foreach($arr as $item)
if(item != "")
$out[] = $item;
return $out;
}
Use this function to filter the output of the explode function
function filter_empty(&$arrayvar) {
$newarray = array();
foreach ($arrayvar as $k => $value)
if ($value !== "")
$newarray[$k] = $value;
$arrayvar = $newarray;
}
Regular expression solutions tend to be much slower than basic text replacement, so i'd replace double seperators with single seperators, trim the string of any whitespace and then use explode:
// assuming $source = '1/2//3/';
$source = str_replace('//', '/', $source);
$source = trim($source);
$parts = explode('/', $source);
No regex overhead - should be reasonably efficient, strlen just counts the bytes
Drop the array_values() if you don't care about indexes
Make it into function explode_interesting( $array, $fix_index = 0 ) if you want
$interesting = array_values(
array_filter(
explode('/', '/1//2//3///4/0/false' ),
function ($val) { return strlen($val); }
));
echo "<pre>", var_export( $interesting, true ), "</pre>";
enjoy, Jeff
PHP's split function is similar to the explode function, except that it allows you to enter a regex pattern as the delimiter. Something to the effect of:
$exploded_arr = split('/\/+/', '1/2//3/');
I usually wrap it in a call to array_filter, e.g.
var_dump(array_filter(explode('/', '1/2//3/'))
=>
array(3) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[3]=>
string(1) "3"
}
Be aware, of course, that array keys are maintained; if you don't want this behaviour, remember to add an outer wrapper call to array_values().