Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

finding nth array element 1

Status
Not open for further replies.

santanudas

Technical User
Mar 18, 2002
121
GB
Hi all,
What would be the PHP equivalent of this Perl construct:
Code:
$ENV{"PATH"} = "/bin:/usr/bin";
my $ls = `/bin/ls  /path/to/dir/some_dir/`;
my @images = split /\n/, $ls;
my $name = "some_file.jpg";

my ($position, %pics);
$pics{$images[$_]} = $_ for 0 .. $#images;
$position = $pics{ $name };
all it's doing is filing in the array (i.e. @images) with values from “ls” command and then finding the position (i.e. $position) of a given file (i.e. some_file.jpg) in that array. How to rewrite that in PHP? Sorry if it's dumb questions and too easy to do in PHP but it'd be a great help for me if someone can show show me how to. Thanks in advance for your time helping me.
 
two methods for you to consider. one closely allied to your code, the other pure php and platform independent

Code:
<?php
$ls = `/bin/ls  /path/to/dir/some_dir/`;
$images = explode ("\n", $ls);
$name = "some_file.jpg";
if (false !== ($pos = array_search($name, $images))){
	echo "$name is at position $pos of the array";
} else {
	echo "$name was not found in the directory";
}
?>

Code:
or
<?php
$fh = opendir("/path/to/dir/some_dir/") or die ("cannot open directory");
while (false !== ($file = readdir($fh))){
	if ($file != "." && $file !=".." && !is_dir($file)){
		$images[] = $file;
		if ($file == $name) $pos = count($images)-1;
	}
}
if (isset($pos)){
	echo "$name is at position $pos of the array";
} else {
	echo "$name was not found in the directory";
}
?>
 
actually, method 1 can be improved upon whilst still keeping to the spirit of your code

Code:
<?php
$ls = '/bin/ls  /path/to/dir/some_dir/'; //convert from shell_exec to a cmd string
exec($ls, $images); //no explode/split overhead
$name = "some_file.jpg";
if (false !== ($pos = array_search($name, $images))){
    echo "$name is at position $pos of the array";
} else {
    echo "$name was not found in the directory";
}
?>
 
actually, method 1 can be improved upon whilst still keeping to the spirit of your code
Yes you right and many thanks for your quick replay. It worked like a charm. I've just started PHP, so still learning to use (and find out) correct php function(s) to make things happen. Thanks once again.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top