How to find name of the file with particular extesion in array - php

I have multiples values in array and i want get one of name which in array.
Ex: - $val = array('test.mp4','abc.avi','xyz.3gp','abc.csv');
Now i want get the name of 'abc.csv' in $name.
Please help me to find the value which is ending with extension .csv.

I think this simple code can help
$val = array('test.mp4','abc.avi','xyz.3gp','abc.csv');
$extension = '.csv';
$name = '';
foreach ($val as $value) {
if (strpos($value, $extension) !== false) {
$name[] = $value;
}
}
print_r($name);

Try this
$list = array('test.mp4','abc.avi','xyz.3gp','abc.csv');
$name = '';
foreach ($list as $item) {
if (strrpos($item, '.csv') === 3) {
$name = $item;
}
}
echo $name;

$val = array('test.mp4', 'abc.avi', 'xyz.3gp', 'abc.csv');
foreach ($val as $value) {
$tmp = strrpos($value, ".csv");
echo substr($value, 0, $tmp );
}

foreach ($val as $value) {
$extension = explode(".", $value);
if($extension[1] == "csv"){
echo $value;
}
}

foreach ($val as $item) {
$file_extensions = explode(".", $value);
if(end($file_extensions) == 'csv'){
$allCSVFilse[] = $item;
}
}
print_r($allCSVFiles);

Related

PHP How to merge array element with next while maintaining order?

$array = ['coke.','fanta.','chocolate.'];
foreach ($array as $key => $value) {
if (strlen($value)<6) {
$new[] = $value." ".$array[$key+1];
} else {
$new[] = $value;
}
}
This code doesn't have the desired effect, in fact it doesn't work at all. What I want to do is if an array element has string length less than 5, join it with the next element. So in this case the array should turn into this:
$array = ['coke. fanta.','chocolate.'];
$array = ['coke.','fanta.','chocolate.', 'candy'];
$new = [];
reset($array); // ensure internal pointer is at start
do{
$val = current($array); // capture current value
if(strlen($val)>=6):
$new[] = $val; // long string; add to $new
// short string. Concatenate with next value
// (note this moves array pointer forward)
else:
$nextVal = next($array) ? : '';
$new[] = trim($val . ' ' . $nextVal);
endif;
}while(next($array));
print_r($new); // what you want
Live demo
With array_reduce:
$array = ['coke.', 'fanta.', 'chocolate.', 'a.', 'b.', 'c.', 'd.'];
$result = array_reduce($array, function($c, $i) {
if ( strlen(end($c)) < 6 )
$c[key($c)] .= empty(current($c)) ? $i : " $i";
else
$c[] = $i;
return $c;
}, ['']);
print_r($result);
demo
<pre>
$array = ['coke.','fanta.','chocolate.'];
print_r($array);
echo "<pre>";
$next_merge = "";
foreach ($array as $key => $value) {
if($next_merge == $value){
continue;
}
if (strlen($value)<6) {
$new[] = $value." ".$array[$key+1];
$next_merge = $array[$key+1];
} else {
$new[] = $value;
}
}
print_r($new);
</pre>
Updated Code after adding pop after chocolate.
<pre>
$array = ['coke.','fanta.','chocolate.','pop'];
print_r($array);
echo "<br>";
$next_merge = "";
foreach ($array as $key => $value) {
if($next_merge == $value){
continue;
}
if (strlen($value)<6 && !empty($array[$key+1])) {
$new[] = $value." ".$array[$key+1];
$next_merge = $array[$key+1];
} else {
$new[] = $value;
}
}
print_r($new);
<pre>
You need to skip the iteration for the values that you have already added.
$array = ['coke.', 'fanta.', 'chocolate.'];
$cont = false;
foreach ($array as $key => $value) {
if ($cont) {
$cont = false;
continue;
}
if (strlen($value) < 6 && isset($array[$key+1])) {
$new[] = $value.' '.$array[$key+1];
$cont = true;
}
else {
$new[] = $value;
}
}
print_r($new);

Unable to print array outside foreach loop

$val = array();
foreach ($value as $key) {
$nested = $this->Mdl_mymodel->arr($key);
if($nested != NULL) {
$n = 0;
foreach ($nested as $nest) {
$n++;
$val[$n] = $nest->num;
}
}
else {
$val = '';
}
print_r($val);
}
print_r($val);
Here $val inside the loop is printed but outside it is empty. I think i am missing something. Please help!
Note: I am using codeigniter.
$val = array();
foreach ($value as $key) {
$nested = $this->Mdl_mymodel->arr();
if($nested != NULL) {
$n = 0;
foreach ($nested as $nest) {
$n++;
$val[$n] = $nest->num;
}
}
else {
// $val = ''; Commented this line because you have already
// initialized $val. If you do not get records,
// it will return as blank array.
}
print_r($val);
}
print_r($val);

php echo results in alphabetical order

This code below will echo the keyword in each file, Is it possible to get the results (Keyword from each file) to display in alphabetical order.
<?php
$files = (glob('{beauty,careers,education,entertainment,pets}/*.php', GLOB_BRACE));
$selection = $files;
$files = array();
$keywords = $matches[1];
foreach ($selection as $file) {
if (basename($file) == 'index.php') continue;
if (basename($file) == 'error_log') continue;
$files[] = $file;
}
foreach($files as $file) {
$title = str_replace('-', ' ', pathinfo($file, PATHINFO_FILENAME));
$content = file_get_contents($file);
if (!$content) {
echo "error reading file $file<br>";
}
else {
preg_match("/keywords = \"(.*?)\"/i", $content, $matches);
$keywords = $matches[1];
}
$results .= '<li>'.$keywords.'</li>';
}
?>
<?=$results?>
Use sort() to sort the keyword array:
$keywords = array();
// ...
$keywords[] = $matches[1];
sort($keywords);
use sort() on $keywords. There's some spelling mistakes and unused varaibles. You need to not build your $results HTML until all the files are processes, so move that $results = '' out of the foreach loop that processes the files, then sort, then foreach the keywords and build up $results.
<?php
$selection = (glob('{beauty,careers,education,entertainment,pets}/*.php', GLOB_BRACE));
$files = array();
// $keywords = $matches[1];
foreach ($selection as $file) {
if (basename($file) == 'index.php') continue;
if (basename($file) == 'error_log') continue;
$files[] = $file;
}
foreach($files as $file) {
//$title = str_replace('-', ' ', pathinfo($file, PATHINFO_FILENAME));
$content = file_get_contents($file);
if (!$content) {
echo "error reading file $file<br>";
}
else {
preg_match("/keywords = \"(.*?)\"/i", $content, $matches);
$keywords[] = $matches[1];
}
}
$results = '';
sort($keywords); //comment this out to see the effects of the sort()
foreach($keywords as $_k) {
$results .= '<li>'.$_k.'</li>';
}
?>
<?=$results?>

Recursive directory listing in ownCloud

I'm writing code that I'd like to recursively list directories. So far I've written code that lists level 1 directories. Does anyone have any ideas about how I can recurse infinitely?
$res = OC_Files::getDirectoryContent('');
$list = array();
foreach($res as $file) {
if ($file['type'] == 'dir') {
$res1 = OC_Files::getDirectoryContent('/'.$file['name']);
foreach($res1 as $res2) {
if ($res2['type'] == 'file') $list[] = $file['name'].'/'.$res2['name'];
}
} else $list[] = $file['name'];
}
foreach($list as $entry)
echo $entry.'</br>';
Try this:
function traverse_directory($dir) {
$res = OC_Files::getDirectoryContent($dir);
$list = array();
foreach($res as $file) {
if ($file['type'] == 'dir') {
traverse_directory($dir . '/' . $file['name'])
} else {
$list[] = $file['name'];
}
}
foreach($list as $entry) {
echo $entry.'</br>';
}
}
traverse_directory('');

problem with parse_ini_file

I'm using parse_ini_file() to read an ini file that has this line:
[admin]
hide_fields[] = ctr_ad_headerImg
the problem is that it outputs it like,
[admin]
hide_fields = Array
can someone help me out? how do I read "hide_fields[]" like a string?
Best Regards
Joricam
My code is:
$ini_array = parse_ini_file($config_path, true);
//print_r($ini_array);
//echo $ini_array["default_colors"]["sitebg"];
$ini_array["default_colors"]["sitebg"]="#000000";
write_php_ini($ini_array,$config_path);
Functions that Im using:
function write_php_ini($array, $file)
{
$res = array();
foreach($array as $key => $val)
{
if(is_array($val))
{
$res[] = "[$key]";
foreach($val as $skey => $sval) $res[] = "$skey = ".(is_numeric($sval) ? $sval : ''.$sval.'');
}
else $res[] = "$key = ".(is_numeric($val) ? $val : ''.$val.'');
}
safefilerewrite($file, implode("\r\n", $res));
}
//////
function safefilerewrite($fileName, $dataToSave)
{ if ($fp = fopen($fileName, 'w'))
{
$startTime = microtime();
do
{ $canWrite = flock($fp, LOCK_EX);
// If lock not obtained sleep for 0 - 100 milliseconds, to avoid collision and CPU load
if(!$canWrite) usleep(round(rand(0, 100)*1000));
} while ((!$canWrite)and((microtime()-$startTime) < 1000));
//file was locked so now we can store information
if ($canWrite)
{ fwrite($fp, $dataToSave);
flock($fp, LOCK_UN);
}
fclose($fp);
}
}
Parse_ini_file() does handle such identifiers. It correctly converts them into arrays on reading the ini file:
print_r(parse_ini_string("hide_fields[] = ctr_ad_headerImg"));
Will generate:
Array
(
[hide_fields] => Array
(
[0] => ctr_ad_headerImg
)
The entry can be accessed as $cfg["hide_fields"][0] in PHP. The problem is that the ini file output function you have chosen this time does not understand array attributes.
Since you are probably interested in workarounds instead of using an appropriate tool, apply this conversion loop on your ini data:
// foreach ($sections ...) maybe
foreach ($cfg as $key=>$value) {
if (is_array($value)) {
foreach ($value as $i=>$v) {
$cfg["$key"."[$i]"] = $v;
}
unset($cfg[$key]);
}
}
And save it afterwards.
Edited code
function write_php_ini($array, $file)
{
$res = array();
foreach($array as $key => $val)
{
if(is_array($val))
{
$res[] = "[$key]";
foreach($val as $skey => $sval) {
if (is_array($sval)) {
foreach ($sval as $i=>$v) {
$res[] = "{$skey}[$i] = $v";
}
}
else {
$res[] = "$skey = $sval";
}
}
}
else $res[] = "$key = $val";
}
safefilerewrite($file, implode("\r\n", $res));
}
//////
function safefilerewrite($fileName, $dataToSave)
{
file_put_contents($fileName, $dataToSave, LOCK_EX);
}

Categories