Check if value exists in Array then save as variable [duplicate] - php

This question already has an answer here:
match exact number in string (and no partial match inside bigger numbers)
(1 answer)
Closed 3 months ago.
Been trying for a while on how to check if a value exists in an array and if so, assign it to a variable to be inserted into the database.
I have the searching working although I can't seem to grab the correct value from the array to which I then need to insert.
Here's where I'm searching for the ID to search by:
{
"questionName": "_questionImgPhoto_176471",
"questionID": "471",
}
Here's the array example:
[0]"/insert/ImgID_466.png"
[1]"/insert/ImgID_471.png"
I am checking if questionID 471 exists somewhere in the array string, if so, insert that row. I am struggling on that part.
So for the insert on questionID 466, the img with 466 in the string will attach to it and so forth.
As you can see 471 does exist in the array example so it should grab that row, here's a snippet of my code below:
for ($i=0; $i < count($content->formValuesT); $i++)
{
if(strpos($content->formValuesT[$i]->questionValue, 'blob') !== false )
{
foreach($content->images_to_upload[$i] as $index => $string) {
if (strpos($string, $content->formValuesT[$i]->questionID) !== FALSE)
{
$file_to_upload = $content->images_to_upload[$i];
}
else
{
echo "wont insert";
}
}
}
}
Has anyone got some pointers or ideas on how to achieve the above? I just can't wrap my head around the practical side of it! in theory I think this is the correct route.
The $file_to_upload is what will be uploaded per row.
Thanks

You can search an array for a specific pattern. Here I made a simple helper function to return the first match or NULL.
$imagesToInsert = ["/insert/ImgID_466.png", "/insert/ImgID_471.png"];
$getImageForId = function(int $id, array $images): ?string {
$matches = preg_grep("/ImgID_{$id}\.png/", $images);
return $matches ? reset($matches) : null;
};
var_dump($getImageForId(471, $imagesToInsert));
var_dump($getImageForId(466, $imagesToInsert));
var_dump($getImageForId(777, $imagesToInsert));
Output
string(21) "/insert/ImgID_471.png"
string(21) "/insert/ImgID_466.png"
NULL

Related

Php count conditions inside loop [duplicate]

This question already has answers here:
PHP - count specific array values
(10 answers)
Closed 9 days ago.
Close my question when it´sdifferent to this not duplicater, the case it´s different in all :
PHP - count specific array values
My question not the same
I have this array for example :
$array_test=array("gren","green","red","red","green","blue");
My idea is know inside loop number of elementos with the condition i want, the array for show it´s more complex and this is only example for understand i need, because try different ways with "count" and don´t show right this number in each case.
I try this :
foreach($array_test as $array_ts) {
if($array_ts=="green") { Count number of elements green /// }
if($array_ts=="red") { Count number of elements red /// }
if($array_ts=="blue") { Count number of elements blue /// }
}
Thank´s for the help, regards.
You can create an array and fill it with the count for each color:
$input = ["gren","green","red","red","green","blue"];
$count = [];
foreach ($input as $color) {
if (array_key_exists($color, $count)) {
$count[$color]++;
} else {
$count[$color] = 1;
}
}
$count will contain:
["green"=>3, "red"=>2, "blue"=>1]

Find out if string matches array key, return value for that key

I am working on an import script that needs to evaluate whether the set string fits with the possible values the backend field can have.
More exactly what I have is this array of committes:
$committees = array(
'Ämter' => 1,
'Abteilungen' => 2,
'Konservatoren' => 3,
'Dienstagssitzung' => 4,
);
and now I need to figure out if a string saved in
variable $category matches any key in that array. If it does match one of the entries, I need it to return the value (1, 2, 3 or 4) that goes with that key.
I read up about it here on Stackoverflow and found plenty examples to see if a value equals one in an array, for example:
preg_match array items in string?
and tried to follow those along.
I tried
$committeesKeys = '/(' . implode('|', array_keys($committees)) . ')/';
$matches = preg_match($committeesKeys, $category);
but that only returned how many matches it found?
I also tried
$input = preg_quote($category, '/');
$matches = preg_filter('/'.$input.'/', null, $committees);
as that was suggested somehwere else, can't find the link anymore, but that returned an empty array.
I am new to all of this so might be totally wrong here.
Can anybody tell me how I can do this, or where I can find an answer to the question? I might just not have found it, my brain is rather tired right now...
I feel that I have right to post that as answer accepted :-) :
echo (isset($committees[$category]))?$committees[$category]:'There is no '.$category.' category';
you can do something like this:
function getValue($category){
if (array_key_exists($category, $committees)){
return $committees[$category]; //the value you want
}
}
Hope this helps :)
preg_match() has a 3rd argument which will allow you to save capture groups into a numerical array. However, if you want to compare a string directly you can simply use a loop and strcmp or === which will probably work faster since preg_match has to compile the regex you define in the first argument. My solution for this problem would look like:
$found = FALSE;
foreach ( $committees as $name=>$number ) {
if ( $name === $category ) {
$found = $number;
}
}
return $found;
You make it difficult by not showing what is in the category matches.
Maybe something like this.
$results = array_intersect ($matches,$committees );

Unset element in array [duplicate]

This question already has answers here:
PHP array delete by value (not key)
(20 answers)
Closed 9 years ago.
I want to unset 1 element in the array.
If for example I use GET and ?group=k
How do I unset "k" in the array?
This is the array:
$groups_array = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','a2','b2','c2','d2','e2','f2');
I have tried
if(isset($_GET['group'])) {
unset($groups_array[1]);
$new_groupps_array = array_values($groups_array);
}
which works fine but where it shows [1] it needs to be a letter so I know how to unset it?
Hope you understand
many thanks
Example, if you wanted to delete 'a' value, you simply do:
$key = array_search('a', $groups_array); // search for key of my value
if($key !== false){
unset($groups_array[$key]);
}
Can you try this, You can use array_search function to retrieve the value based key and unset the array accordingly.
if(isset($_GET['group'])) {
$key = array_search ($_GET['group'], $groups_array);
unset($groups_array[$key ]);
$new_groupps_array = array_values($groups_array);
}

Check if an array contains another array with PHP [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Checking if an array contains all elements of another array
I have posted something like this to the Stackoverflow before, but the answers do not fully satisfy me. That's why I'm posting the question again, but changing the question all along.
Some people helped me to construct a function that checks if an array($GroupOfEight[$i]) that is an element of a multidimensional array($GroupOfEight) equals another array($stackArray), disregarding the number ordering in the arrays.
However, what I need to check is whether the mentioned array($stackArray) contains any another array($GroupOfEight[$i]) in the multidimensional array($GroupOfEight) or not, that means main array($stackArray) can consist more elements than subarrays($GroupOfEight[$i]).
Here is the one working code that I've gathered so far, but need to be modified to the version I want:
<?php
$GroupOfEight = array (
array(0,1,3,2,4,5,7,6),
array(4,5,6,7,15,12,13,14),
array(12,13,15,14,8,9,11,10),
array(2,6,14,10,3,7,15,11),
array(1,3,5,7,13,15,9,11),
array(0,4,12,8,1,5,13,9),
array(0,1,3,2,8,9,11,10)
);
$stackArray = array(0,4,12,1,9,8,5,13,9,2,5,2,10);
/*$stackArray gets value with POST Method by URL parameter.
This is just the example. As you see this array contains
$GroupOfEight[4], and also it contains many other numbers.*/
/* The function given below checks if $stackArray equals any
of the subarrays of $GroupOfEight. However, we want to check
if $stackArray caontains any of the subarrays of function.
If it does, function should return the index number, if it
doesnt it should return -1.*/
function searcheight($stackArray,$GroupOfEight){
for($i=0; $i<count($GroupOfEight);$i++){
$containsSearch = (count(array_intersect($stackArray,$GroupOfEight[$i])) == count($stackArray) && count(array_intersect($stackArray,$GroupOfEight[$i])) == count($GroupOfEight[$i]));
if($containsSearch){
return $i; //This specifies which index in GroupOfEight contains a matching array
}
}
return -1;
}
// Calling the function that is given above.
echo searcheight($stackArray,$GroupOfEight);
?>
Any logical ideas or solutions will kindly be much appreciated. Thanks.
This one is fast:
function contains_array($array){
foreach($array as $value){
if(is_array($value)) {
return true;
}
}
return false;
}
You can try
$GroupOfEight = array(
array(0,1,3,2,4,5,7,6),
array(4,5,6,7,15,12,13,14),
array(12,13,15,14,8,9,11,10),
array(2,6,14,10,3,7,15,11),
array(1,3,5,7,13,15,9,11),
array(0,4,12,8,1,5,13,9),
array(0,1,3,2,8,9,11,10));
$stackArray = array(0,4,12,1,9,8,5,13,9,2,5,2,10);
function searcheight($stackArray, $GroupOfEight) {
$list = array();
for($i = 0; $i < count($GroupOfEight); $i ++) {
$intercept = array_intersect($GroupOfEight[$i], $stackArray);
$len = count($intercept);
if ($len % 4 == 0) {
$list[$i] = $len;
}
}
arsort($list);
if (empty($list))
return - 1;
return key($list);
}
echo searcheight($stackArray, $GroupOfEight);
Output
5

I need to get a count of values (grouped) in a csv column

I need to get a count of the first column's values. These ID's might or might not exist in any given .csv file I receive. So I need to loop through the .csv file looking at the first column and either adding it to a holding array ($PWSs) if it doesn't exist or incrementing the count in this holding array if I've already added it.
I have the first loop using fgetcsv()..this works for cracking into the file:
$PWSs = array();
$handle2 = fopen ($uploadfileandpath,"r");
while ($field2array = fgetcsv ($handle2, 130000, ","))
{
// Here is where I would add value or increment $PWSs array
while (?)
{
if ($field2array[0] != ?)
{
// Add or increment
}
}
}
Here is actual data. The first column has IDs for Public Water Systems. I need to count them.
"00513","08/13/2009","090834311A","R","4","OR1000x6","N","N","E",,1,".73","COLILERT"
"00513","08/13/2009","090834312A","R","39","OR1000x6","N","N","E",,1,".35","COLILERT"
"00154","08/13/2009","090835401A","R","300 Falls Road","OR100016","N","N","E",,1,".10","COLILERT"
"95343","08/13/2009","090835601A","R","Room 1 Sink","OR1000x6","N","N","E",,1,,"COLILERT"
"94585","08/14/2009","090837701A","R","Kitchen","OR1000x6","N","N","E",,1,,"COLILERT"
"94704","08/14/2009","090837801A","R","Outside Tap","OR1000x6","N","N","E",,1,,"COLILERT"
"01430","08/14/2009","090838201A","R","100 Deer Park Ln OT","OR1000x6","N","N","E",,1,,"COLILERT"
"00625","08/14/2009","090839001A","R","Dano and N Rose","OR100016","N","N","E",,1,".35","COLILERT"
"00405","08/17/2009","090840301A","R","Westmont Drive","OR100016","N","N","E",,1,".28","COLILERT"
"01031","08/17/2009","090840401A","R","Unit 2 Faucet","OR100016","N","N","E",,1,,"COLILERT"
"00625","08/17/2009","090840601A","R","Luman Road","OR1000x6","N","N","E",,1,".35","COLILERT"
"00513","08/17/2009","090841001A","R","40","OR1000x6","N","N","E",,1,".18","COLILERT"
"00513","08/17/2009","090841002A","R","10","OR1000x6","N","N","E",,1,".16","COLILERT"
$fh = fopen('file.csv', 'rb');
$PWS = array();
while($row = fgetcsv($fh)) {
$PWS[$row[0]]++;
}
Basically it'll populate the PWS using the first column values as keys, and increment them as they come along. Afterwards, given your sample csv above, you'd end up with
$PWS = array(
'00513' => 4
'00154' => 1
'95343' => 1
'94585' => 1
etc...
);
function get_pws()
{
$PWSs = array();
$handle2 = fopen ($uploadfileandpath,"r");
while ($field2array = fgetcsv ($handle2, 130000, ","))
{
if(!in_array($field2array[0], $PWSs))
{
array_push($PWSs, array('key'=>$field2array[0], 'count'=>1));
}
else
{
foreach($PWSs as &$PWS)
{
if($PWS['key'] == $field2array[0])
{
++$PWS['count'];
}
}
}
}
return $PWSs;
}
I haven't actually run and tested this script, so hopefully it works and it's what you're looking for ;)
Edit: Thanks for pointing that out dq. Again, I haven't tested it (not on a machine with PHP installed atm), so hopefully it still works (if it worked in the first place) :P
You only need one while loop. Your outer while loop will stop when it hits the eof, because fgetcsv() will return FALSE.
Then just test for the column to be NULL or "" an empty string. If the column did not exist in the given array, you should use isset() to make sure it exists first in your conditional.

Categories