This question already has answers here:
How can I remove the file extension from each string in a PHP array?
(4 answers)
Closed 3 years ago.
I was wondering if there is any basic solution to remove the endings of all strings in an array?
I could do it with a foreach etc. but I'm looking for something somewhat smaller in code.
For example, converting this:
Array ( [0] => test1.csv [1] => test2.csv [2] => test3.csv )
To this:
Array ( [0] => test1 [1] => test2 [2] => test3 )
try this :
<?php
$arr = array ('test1.csv', 'test2.csv', 'test3.csv' );
array_walk($arr, function(&$val){
$val = str_replace('.csv','',$val);
return $val;
});
You can use basename() which will remove extensions or unwanted characters from filenames.
$files = ['test1.csv', 'test2.csv', 'test3.csv'];
$filesWithoutExt = array_map(function($e) { return basename($e, '.csv'); }, $files);
var_dump($filesWithoutExt);
array(3) {
[0] =>
string(5) "test1"
[1] =>
string(5) "test2"
[2] =>
string(5) "test3"
}
Another array_map using pathinfo to return the filename (PATHINFO_FILENAME basename without any extension):
$array = array_map(function($v) { return pathinfo($v, PATHINFO_FILENAME); }, $array);
Related
This question already has answers here:
php sort filenames with an underscore
(3 answers)
Closed 5 years ago.
I have an array of values (keys are not important):
$Array = array("File01","File02","File00","_File03");
I want to sort this by value, to match my Windows file system, e.g.:
Array ( [3] => _File03 [2] => File00 [0] => File01 [1] => File02 )
I have tried asort($Array), but this gives me:
Array ( [2] => File00 [0] => File01 [1] => File02 [3] => _File03 )
Is it possible to sort with underscores first?
try this.. its working.
<?php
$array = array("File01","File02","File00","_File03");
function sortUnderscoreToFront($a, $b) {
if (substr($a, 0, 1) == '_' || substr($b, 0, 1) == '_') {
return ((substr($a,0,1)=='_')?-1:1);
}
return strcmp(strval($a), strval($b));
}
usort($array, 'sortUnderscoreToFront');
echo "<pre>";
print_r($array)."</pre>";
?>
I am matching pairs in regex. $pairs[1] will contain the part before = and $pairs[2] will contain the part after = .
When it gets to &startrow it should start skips rest and start making another pair.
$query= "link=http://abcd.com&efgh&lmkn&startrow=20"
preg_match_all('/(\w+)=([^&startrow]+)/', $query, $pairs);
The above regex stops at & but not at &startrow
Expected Output
$pairs[1][0] = link
$pairs[2][0] = http://abcd.com&efgh&lmkn
$pairs[1][1] =startrow
$pairs[2][1] =20
You don't need a regular expression for this; you need parse_str():
$ php -a
Interactive mode enabled
php > $params = null;
php > parse_str('link=http://abcd.com&efgh&lmkn&startrow=20', $params);
php > var_dump($params);
php shell code:1:
array(4) {
'link' =>
string(15) "http://abcd.com"
'efgh' =>
string(0) ""
'lmkn' =>
string(0) ""
'startrow' =>
string(2) "20"
}
Using following regex:
(\w+)=((?:(?!&startrow).)+)
You are able to catch both parts separately:
preg_match_all('~(\w+)=((?:(?!&startrow).)+)~', $str, $matches, PREG_SET_ORDER);
PHP output:
Array
(
[0] => Array
(
[0] => link=http://abcd.com&efgh&lmkn
[1] => link
[2] => http://abcd.com&efgh&lmkn
)
[1] => Array
(
[0] => startrow=20
[1] => startrow
[2] => 20
)
)
PHP live demo
I don't know why that would make sense, but assuming all you request are well formed and valid, you could do something plain and simple like this ;)
$_GET_RAW = [];
if (!empty($_SERVER['QUERY_STRING'])) {
// split query string into key value pairs
foreach (explode('&', $_SERVER['QUERY_STRING']) as $keyValueString) {
// separate key and value
list($key, $value) = explode('=', $keyValueString);
$_GET_RAW[$key] = $value;
}
}
This question already has answers here:
Turning multidimensional array into one-dimensional array [duplicate]
(11 answers)
Closed 7 years ago.
I have an array as shown below,
How to convert the above array1 into array2 form?
array1
Array
(
[0] => Array
(
[0] => 500 GB
)
[1] => Array
(
[0] => 100 GB
)
)
array2
Array
(
[0] => 500 GB
[1] => 100 GB
)
$yourArray = [[0 => '500 GB'], [0 => '100 GB'], [1 => '200 GB']];
$result = array_filter(
array_map(
function($element) {
if (isset($element[0])) {
return $element[0];
}
return;
},
$yourArray
),
function($element) {
return $element !== null;
}
);
echo var_dump($result); // array(2) { [0]=> string(6) "500 GB" [1]=> string(6) "100 GB" }
This will work only with php >= 5.4 (because of array short syntax). If you're running on older versione, just substitute [] with array()
Explaination
array_filter is used to exclude certain values from an array (by using a callback function). In this case, NULL values that you get from array_map.
array_map is used to apply a function to "transform" your array. In particular it applies a function to each array element and returns that element after function application.
This question already has answers here:
Remove duplicates from Array
(2 answers)
Closed 9 years ago.
I have an array like this
Array
(
[0] => u1,u2
[1] => u2,u1
[2] => u4,u3
[3] => u1,u3
[4] => u1,u2
)
I want to remove similar values from the array
I want an out put like
Array
(
[0] => u1,u2
[1] => u4,u3
[2] => u1,u3
)
I tried to loop thru the input array, sort the value of the indexes alphabetically and then tried array_search to find the repeated values. but never really got the desired output
any help apprecated
You cannot use array_unique() alone, since this will only match exact duplicates only. As a result, you'll have to loop over and check each permutation of that value.
You can use array_unique() to begin with, and then loop over:
$myArray = array('u1,u2', 'u2,u1', 'u4,u3', 'u1,u3', 'u1,u2');
$newArr = array_unique($myArray);
$holderArr = array();
foreach($newArr as $val)
{
$parts = explode(',', $val);
$part1 = $parts[0].','.$parts[1];
$part2 = $parts[1].','.$parts[0];
if(!in_array($part1, $holderArr) && !in_array($part2, $holderArr))
{
$holderArr[] = $val;
}
}
$newArr = $holderArr;
The above code will produce the following output:
Array (
[0] => u1,u2
[1] => u4,u3
[2] => u1,u3
)
Use array_unique() PHP function:
http://php.net/manual/en/function.array-unique.php
Use the function array_unique($array)
array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )
php manual
since u1,u2 !== u2,u1
$array=array('u1,u2','u2,u1','u4,u3','u1,u3','u1,u2');
foreach($array as $k=>$v)
{
$sub_arr = explode(',',$v);
asort($sub_arr);
$array[$k] = implode(',',$sub_arr);
}
$unique_array = array_unique($array);
//$unique_array = array_values($unique_array) //if you want to preserve the ordered keys
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Convert a string into list of arrays
I have a string code=AA&price=10&user_id=5.initially i exploded first with & and then by = but i getting.
array(
[0] =>code
[0] =>AA
[0] =>price
[0] =>10
[0] =>user_id
[0] =>5
)
My aim is to show
array(
[code] => AA
[price] => 10
[user_id] => 5
)
parse_str($str, $values);
var_dump($values);
You are parsing a URL encoded format, use the already existing parse_str to parse it.
$string = 'code=AA&price=10&user_id=5';
$params = array();
parse_str($string, $params);
print_r($params);
http://php.net/manual/en/function.parse-str.php
parse_str — Parses the string into variables
parse_str('code=AA&price=10&user_id=5', $outputArray);