PHP - Search in specific array value - arrays

I want to Search in Array value by in_array Function and For loop. My code:
$input = "a";
$arrays = array("cdf","abs","tgf");
$counter = count($arrays);
for ($i=0; $i<$counter; $i++){
if(in_array($input,$arrays) !== true){
echo "Found <br>";
} else {
echo "Not Found";
}
}
Output:
Not Found
Found
Not Found
But, if(in_array($input,$arrays[$i]) !== true) not working.

The reason in_array("a", "cdf"), which is what in_array($input, $arrays[$i]) could become, isn't working is because "cdf" isn't an array.
Are you trying to find array elements in $arrays that contain the letter a?
In that case you should search array elements with strpos() to determine if a string contains another string. You can also use foreach instead of for if iterating over the array is all you want to do.
$input = "a";
$arrays = array("cdf","abs","tgf");
foreach ($arrays as $key => $value)
{
if (strpos($value, $input) !== false)
echo "Found in $key<br>";
else
echo "Not Found<br>";
}

Related

Laravel make array of arrays

How get an array of many array ? foreach line 0-1-2-3(4-5 same object actually), actually objects.
How make it for get:
[ 1[] 2[] 3[4[]5[]] ]
Php code (laravel):
$array = array();
foreach($users as $u)
{
$x = User::where('xxx', 'xxx')->toArray();
array_push($array, $x);
}
return $array;

perl array not populating, despite hours of tinkering

Um...I have the following code snippet, and was wondering why the second subroutine, search($$) fails to yield results...while the first routine, search_item($$$), performs admirably (imo).
########################
# generate and return a list of users which match only
# one criteria (eg: eyes=2)
#
# $users is a reference to an array of 6-digit hexidecimal user IDs (eg: 000001, 000002, etc)
# $name is the name of the key (or field) to find (eg: 'eyes')
# $value (eg: 2) is compared with the value stored in the key
# if $value matches what's in the $name'd key, then add the uid to a list
sub search_item($$$) {
my ($users, $name, $value) = #_;
my #searched;
foreach my $uid (#$users) {
my %ustats = user::getUserStats($uid);
if ($ustats{$name} eq $value) { push #searched, $uid; }
}
return #searched;
}
########################
# generate and return a list of users which match
# many criteria (eg: eyes=2, hair=1, etc)
#
# $users is a reference to an array of user IDs (eg: 000001, 000002, etc)
# $terms is a reference to an array of search terms (eg: $terms[0] = "eyes=2";)
sub search($$) {
my $users = $_[0]; # an array reference
my $terms = $_[1]; # an array reference
my #searched;
my $first = 1;
foreach my $term (#$terms) {
# since #$terms is an array of scalars, in the format of 'name=value' pairs
my $name = $term; $name =~ s/=(.)*//;
my $value = $term; $value =~ s/$name=//;
if ($first) {
# search the given list reference ($users)
#searched = search_item($users, $name, $value);
$first = 0; # set to 0 cause now we gotta use #searched
} else {
# otherwise use a reference to #searched
#searched = search_item(\#searched, $name, $value);
}
}
return #searched;
}
i have setup the data so the code should return 1 hit. the data is correct and underlying functions (eg: getUserStats($)) also perform flawlessly.
both user 000001 and 969696 have eyes=2 all others eyes=1 and
user ID 000001 is gender=1, all others gender=0
so...if i write:
my #users = getUsers();
foreach my $uid (search_item(\#users, 'eyes', 2)) {
print "$uid<br>\n";
}
i get 2 hits of a total of 6 users in my database (this IS a correct result, of course). satisfied with those results, I run the search routine.
my #terms = ('eyes=2', 'gender=1'); # gender=0 is a boy. 1 is a girl
my #sResults = search(\#users, \#terms);
if (#sResults) {
foreach my $uid (#sResults) {
print "$uid<br>\n";
}
} else {
print "nothing found!<br>\n";
}
i always see "nothing found!" when i pray and hope to see "000001" instead... :(
this seems like legit code....so....whud am i doin wrong guys??? am i not derefencing something correctly? or...is the dereferencing / referencing the source of my dilema? i loath pointers...however incredibly useful :p
Your code does actually work if you pass correct parameters. My best guess is that the strings like eyes=2 that you're using contain spurious whitespace such as a trailing newline
Here's the test program that I used to work on your subrouitines
use strict;
use warnings;
use 5.010;
my %users = (
'000001' => { eyes => 2, gender => 1 },
'000002' => { eyes => 1, gender => 0 },
'000003' => { eyes => 1, gender => 0 },
'000004' => { eyes => 1, gender => 0 },
'969696' => { eyes => 2, gender => 0 },
);
sub user::getUserStats {
my ( $uid ) = #_;
%{ $users{$uid} };
}
########################
# generate and return a list of users which match only
# one criteria (eg: eyes=2)
#
# $users is a reference to an array of 6-digit hexidecimal user IDs (eg: 000001, 000002, etc)
# $name is the name of the key (or field) to find (eg: 'eyes')
# $value (eg: 2) is compared with the value stored in the key
# if $value matches what's in the $name'd key, then add the uid to a list
sub search_item($$$) {
my ( $users, $name, $value ) = #_;
my #searched;
foreach my $uid ( #$users ) {
my %ustats = user::getUserStats( $uid );
if ( $ustats{$name} eq $value ) { push #searched, $uid; }
}
return #searched;
}
########################
# generate and return a list of users which match
# many criteria (eg: eyes=2, hair=1, etc)
#
# $users is a reference to an array of user IDs (eg: 000001, 000002, etc)
# $terms is a reference to an array of search terms (eg: $terms[0] = "eyes=2";)
sub search($$) {
my $users = $_[0]; # an array reference
my $terms = $_[1]; # an array reference
my #searched;
my $first = 1;
foreach my $term ( #$terms ) {
# since #$terms is an array of scalars, in the format of 'name=value' pairs
my $name = $term;
$name =~ s/=(.)*//;
my $value = $term;
$value =~ s/$name=//;
if ( $first ) {
# search the given list reference ($users)
#searched = search_item( $users, $name, $value );
$first = 0; # set to 0 cause now we gotta use #searched
}
else {
# otherwise use a reference to #searched
#searched = search_item( \#searched, $name, $value );
}
}
return #searched;
}
my $users = [ keys %users ];
say for search( $users, [ 'eyes=2', 'gender=1' ] );
output
000001
Here's how I would write similar subroutines that behave identically and take the same parameters, but there is a lot in the design of this application that is less that optimal
sub search_item {
my ( $users, $name, $value ) = #_;
grep {
my %ustats = user::getUserStats( $_ );
$ustats{$name} eq $value;
} #$users;
}
sub search {
my ($users, $terms) = #_;
my #searched;
for my $term ( #$terms ) {
my ($name, $value) = split /=/, $term;
#searched = search_item( $users, $name, $value );
$users = \#searched;
}
#searched;
}
but I think user::getUserStats should be called User::get_user_stats (because Perl reserves capital letters for global identifiers such as package names) and it should return a reference to a hash instead of just a list

First and last regex match

Hi I have a problem with my program, I have wrote the code below and it returns the expected result. However I only am intrested in the first and last occurance of the matches. How would I go about doing this?
foreach (#array)
{
$element = $_;
foreach(#array2)
{
if($_ =~ s/($element)//ig)
{
print "$_ \n";
}
}
}
Currently the loop goes through every element in the array finds it in the second array and prints the whole line. It returns the expected result, however I want the first match and last match.
foreach my $elm2 (#array2) {
my $state = 'start';
my $first, $last;
foreach my $elm1(#array1) {
if (($state eq 'start') && ($elm1 =~ m/$elm2/i)) {
$first = "$elm1";
$state = 'last';
}
elsif (($state eq 'last') && ($elm1 =~ m/$elm2/i)) {
$last = $elm1;
}
}
print "$elm2,$first,$last\n";
}
Could maybe do this
foreach (#array)
{
$first = "";
$last = "";
$element = $_;
foreach(#array2)
{
if($_ =~ s/($element)//ig)
{
if (!length($first)){
$first = $_;
}
else {
$last = $_;
}
}
}
if (length($first) && length($last)) {
print "\n----------\nfirst = '$first'\nlast = '$last'";
}
}
Totally forgot about grep.
foreach my $elm2 (#array2) {
my #matches = grep(/$elm2/i, #array1);
if (#matches && (scalar (#matches > 1))) {
print "$elm2,$matches[0], $matches[-1]\n";
}
elsif (#matches) {
print "$elm2,$matches[0]\n";
}
else {print "no matches\n";};
}
a bit late but this is what I think you could use
Find first match
if ($_ =~ m/($element)/) { print $1; }
Find last match
if ($_ =~ m/.*($element)/) { print $1; }
Assuming you want to check which elements of #array2 match any of the patterns in #array and print the first and last of those, it is simplest to build an alternation regex from the contents of #array and filter #array2 using that.
Like this
my $re = join '|', #array; # Build a regex
$re = qr/$re/; # Compile it
my #matches = grep /$re/, #array2;
print "$_\n" for #matches[0,-1];

Iterate through a hash and an array in Perl

I have an array and a hash:
#arraycodons = "AATG", "AAAA", "TTGC"... etc.
%hashdictionary = ("AATG" => "A", "AAAA" => "B"... etc.)
I need to translate each element of the array for the corresponding value in hashdictionary. However, I obtain a wrong translation.....
To see the problem, I have printed $codon (each element of the array), but each codon is repeated several times..... and It shouldn't.
sub translation() {
foreach $codon (#arraycodons) {
foreach $k (keys %hashdictionary) {
if ($codon == $k) {
$v = $hashdictionary{$k};
print $codon;
}
}
}
}
I don't know if I've explained my problem well enough, but I can't go on with my code if this doesn't work...
Many thanks in advance.
You appear to be looping through the keys of your hash (also known as a "dictionary") to find your desired key. This defeats the purpose of a hash (also known as a "dictionary") - the primary advantage of which is ultra fast lookups of a key.
Try, instead of
foreach $codon (#arraycodons) {
foreach $k (keys %hashdictionary) {
if ($codon == $k) {
$v = $hashdictionary{$k};
print $codon;
}
}
}
this:
foreach $codon (#arraycodons) {
my $value = $hashdictionary{$codon};
print( "$codon => $value\n" );
}
or:
foreach my $key ( keys %hashdictionary ) {
my $value = $hashdictionary{$key};
print( "$key => $value\n" );
}
my #mappedcodons = map {$hashdictionary{$_}}
grep (defined $hashdictionary{$_},#arraycodons);
or
my #mappedcodons = grep ($_ ne "", map{$hashdictionary{$_} || ""} #arraycodons);
my #words = ("car", "house", "world");
my %dictionary = ("car" => "el coche", "house" => "la casa", "world" => "el mundo");
my #keys = keys %dictionary;
foreach(#words) {
my $word = $_;
foreach(#keys) {
if($_ eq $word) { # eq, not ==
my $translation = $dictionary{$_};
print "The Spanish translation of $word is $translation\n";
}
}
}

perl hash of arrays

I am trying to access elements of an array which is part of a hash.
for my $idx ( 0 .. $#vss ) {
push (#{$vsnhash->{$vss[$idx]}}, $vsports[$idx]);
}
print Dumper(\%$vsnhash);
($VAR1 = {
'name2' => [
'8001',
'8002'
],
'name1' => [
'8000'
]
};
I an able to access the keys with a foreach loop:
foreach my $key ( keys %$vsnhash ) {
print "$key\n";
}
How do I access the array of port numbers ('8001' , '8002') within the hash?
Thank you for the help!
while (my ($k, $v) = each %$vsnhash) {
print "$k: #$v\n";
}
foreach my $key ( keys %$vsnhash ) {
print "$key\n";
foreach my $port (#{$vsnhash->{key}}){
print "Port $port\n";
}
}
$vsnhash{name2}->[0]; #8001
$vsnhash{name2}->[1]; #8002
$vsnhash{name1}->[0]; #8000
Code wise:
foreach my $key (sort keys %vsnhash) {
foreach my $index (0..$#{$key}) {
print "\$vsnhash{$key}->[$index] = " . $vsnhash{$key}->[$index] . "\n";
}
}
The $#{$key} means the last entry in the array #{$key}. Remember that $key is a reference to an array while #{$key} is the array itself.

Resources