hmm i got a homework, its 2 hours and i still have no clue on it :|
like this
$sessions['lefthand'] = 'apple';
$sessions['righthand'] = '';
$sessions['head'] = 'hat';
$sessions['cloth'] = '';
$sessions['pants'] = '';
// here is the homework function
CheckSession('lefthand,righthand,head,cloth,pants');
we have some string "lefthand,righthand,head,cloth,pants"
question is : " how can we check if the five session is not null or exist and display which session is empty ( if there is an empty session ) if all exist then returns a true ?
empty righthand , pants, and cloth.
this is how i think about it
explode it to arrays
check one bye one if !null id there is a
here is the progress that ive made *edit4 , :)
function CheckSession($sessions){
$all_sessions_exist = true;
$keys = explode(',',$sessions);
$error = array();
// Search for Session that are not exist
foreach ($keys as $key) {
if (!isset($_SESSION[$key]) && empty($_SESSION[$key])) {
echo "no $key</br>";
$all_sessions_exist = false;
}
}
return $all_sessions_exist;
}
Thanks for taking a look
Adam Ramadhan
Seeing as it's homework, you won't get the solution. You're on the right track though. explode() it by the delimiter. You can the loop through it using foreach and use empty() to check if they're set. You can access the sessions like $_SESSION[$key]. Keep an array of the ones that match.
function CheckSession($string){
$all_sessions_exist = true; #this will change if one of the session keys does not exist
$keys = explode(',', $string); #get an array of session keys
foreach($keys as $key){
if(isset($_SESSION[$key])) {
if(!empty($_SESSION[$key]))
echo '$_SESSION['.$key.'] is set and contains "'.$_SESSION[$key].'".'; #existing non-empty session key
else echo '$_SESSION['.$key.'] is set and is empty.' ;
}else {
echo '$_SESSION['.$key.'] is not set.'; #key does not exist
$all_sessions_exist = false; #this will determine if all session exist
}
echo '<br />'; #formatting the output
}
return $all_sessions_exist;
}
Just cleaning up your function
function CheckSession($sessions)
{
$session = explode(',',$sessions);
$return = array();
foreach ($session as $s)
{
$return[$s] = (isset($_SESSION[$s]) && !empty($_SESSION[$s]) ? true : false)
}
return $return;
}
$sessions['lefthand'] = 'apple';
$sessions['righthand'] = '';
$sessions['head'] = 'hat';
$sessions['cloth'] = '';
$sessions['pants'] = '';
And the checking part
// here is the homework function
$Results = CheckSession('lefthand,righthand,head,cloth,pants');
Edit
//$value1= false; // Commented out so does not get set
$value2= false; //Still set to a bool
error_reporting(E_ALL);
empty($value1); // returns false but still strikes E_NOTICE ERROR
empty($value2); // returns false with no error
Note, empty does not trigger an error but this example would take affect an a lot of other php functions.
Related
I need one help. I need to verify weather one json array value is present inside another array or not using PHP. I am explaining my code below.
$img=array(
array("iamge"=>"1234_asd.jpg"),
array("iamge"=>"1235_ase.jpg"),
array("iamge"=>"1236_asf.jpg")
);
$imgArr=array(
array("iamgename"=>"1234_asd.jpg"),
array("iamgename"=>"1235_ase.jpg"),
array("iamgename"=>"1236_asf.jpg"),
array("iamgename"=>"1237_asg.jpg")
);
Here I have two array. I need to check any of value from $imgArr array is present inside $img array or not.In case any value is not present it will return false with that image name and if all present it will return omlu true. Please help me.
function bjsearch($img, $seachimg){
$result = true;
if(!in_array($seachimg, $img)){
$result = false;
}
return $result;
}
$found = true;
$image_name = '';
foreach($imgArr as $k=>$im){
$seachInArr = isset($img[$k]) ? $img[$k] : array();
$res = bjsearch($seachInArr, $im['iamgename']);
if($res === false){
$found = false;
$image_name = $im['iamgename'];
}
}
var_dump($found, $image_name);
Working Example: https://3v4l.org/vkAF4
$match = array();
foreach ($imgArr as $imgArray){
foreach ($img as $imgg){
if($imgArray['iamgename'] == $imgg['iamge']){
$match[]=$imgArray['iamgename'];
}
}
}
print_r($match);
I need to identify every instance where a value in one array (needle) occurs in another array (haystack). in_array() seems to be my best option, and the code below works perfectly until I need to use it on rows fetched from a db - it keeps appending values instead of setting them each time it's called.
While I can't actually use unset() in this situation, I was surprised to discover that even that didn't seem to resolve the problem.
UPDATE - Example of what's being returned
I temporarily changed the db values so that $needles has only value per row (in order to make it possible to sort through the values filling up my screen ;-))
False;
False; False; True;
False; False; True; False; True;
False; False; True; False; True; False; True;
False; False; True; False; True; False; True; False;
This works correctly
(I've posted a functional example here)
$needles = array('John', 'Alex');
$haystack = array('John','Alexander','Kim', 'Michael');
foreach ($needles as $needle) {
if (in_array($needle, $haystack) ) {
$Match = 'True';
}
else {
$Match = 'False';
}
}
This keeps appending values - Edited to reflect the code I'm using
$Customer_Categories_Arr = array('Casual','Trendy');
if ($stmt->columnCount()) {
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$Product_Categories_Arr[]=$row["Taste_Category"];
// Use when column contains CSV
// $Product_Categories_Arrx = explode(',', trim($Product_Categories_Arr[0]));
foreach ($Product_Categories_Arr as $Product_Category_Arr) {
if (in_array($Product_Category_Arr, $Customer_Categories_Arr)){
$Matches_Product_Category = "True";
} else {
$Matches_Product_Category = "False";
}
echo $Product_Category_Arr, ', ', $Matches_Product_Category, '; ';
}
}
}
It is not really clear what you are trying to do. But maybe this would help:
$customerCategories = array('Casual', 'Trendy');
if( $stmt->columnCount() ){
while( $row = $stmt->fetch( PDO::FETCH_ASSOC )){
$productCategoryRow = $row[ 'Taste_Category' ];
// If it is not working, try uncommenting the next line
// $productCategories = [];
$productCategories = explode( ',', trim( $productCategoryRow ));
$match = "False";
foreach( $productCategories as $productCategory ){
if( in_array( $productCategory, $customerCategories )){
$match = "True";
}
echo $match . ";";
}
}
}
This prints your result on the screen every time a loop is done. Is this what you mean?
If you want the second block of code to do what the first block of code (which works correctly) does, then the second block should look like this -
if ($stmt->columnCount()) {
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$needle =$row["product_var"];
$Match = "False";
if (in_array($needle, $haystack)){
$Match = "True";
}
}
}
You don't need do use the foreach because that is replaced by the while loop in the second block.
I am going to try an solve this. I think the problem is with:
$needles[]=$row["product_var"];
I think this should be:
$needles=$row["product_var"];
The column "product_var" contains an CSV (as you mentioned), so I can make an example like this:
$csv = "jake;john;alex;kim";
An example with brackets ($needles[]):
for($i=0; $i<5; $i++) {
$needles[] = explode(";", $csv);
echo(count($needles).", ");
}
returns:
1, 2, 3, 4, 5,
edit (for more explaining):
if I use print_r I see the array expanding, exactly how it happens in your example:
step 1: it adds an array to $needles with values ('jake','john','alex','kim')
step 2: it adds an array to $needles, so it contains 2x the values ('jake','john','alex','kim')
step 3: it adds an array to $needles, so it contains 3x the values ('jake','john','alex','kim')
etc.
Now without the brackets ($needles):
for($i=0; $i<5; $i++) {
$needles = explode(";", $csv);
echo(count($needles).", ");
}
This returns:
4, 4, 4, 4, 4,
And every time the array simply contains the values ('jake','john','alex','kim') -which is what you want.
Could this explain the "expanding values"? (or am I just doing something really stupid which has nothing to do with your problem??)
edit:
If this is what is going wrong, then you are adding to an array, instead of only using the new array from $row["product_var"] (hope this makes any sense; it seems I am pretty bad at explaining what's happening).
I am stuck. What I would like to do: In the $description string I would like to check if any of the values in the different arrays can be found. If any of the values match, I need to know which one per array. I am thinking that I need to do a function for each $a, $b and $c, but how, I don't know
if($rowGetDesc = mysqli_query($db_mysqli, "SELECT descFilter FROM tbl_all_prod WHERE lid = 'C2'")){
if (mysqli_num_rows($rowGetDesc) > 0){
while($esk= mysqli_fetch_array($rowGetDesc)){
$description = sanitizingData($esk['descFilter']);
$a = array('1:100','1:250','1:10','2');
$a = getExtractedValue($a,$description);
$b = array('one','five','12');
$b = getExtractedValue($b,$description);
$c = array('6000','8000','500');
$c = getExtractedValue($c,$description);
}
}
}
function getExtractedValue($a,$description){
?
}
I would be very very greatful if anyone could help me with this.
many thanks Linda
It would be better to create each array just once and not in every iteration of the while loop.
Also using the same variable names in the loop is not recommended.
if($rowGetDesc = mysqli_query($db_mysqli, "SELECT descFilter FROM tbl_all_prod WHERE lid = 'C2'")){
if (mysqli_num_rows($rowGetDesc) > 0){
$a = array('1:100','1:250','1:10','2');
$b = array('one','five','12');
$c = array('6000','8000','500');
while($esk= mysqli_fetch_array($rowGetDesc)){
$description = sanitizingData($esk['descFilter']);
$aMatch = getExtractedValue($a,$description);
$bMatch = getExtractedValue($b,$description);
$cMatch = getExtractedValue($c,$description);
}
}
}
Use strpos to find if the string exists (or stripos for case insensitive searches). See http://php.net/strpos. If the string exists it will return the matching value in the array:
function getExtractedValue($a,$description) {
foreach($a as $value) {
if (strpos($description, $value) !== false) {
return $value;
}
}
return false;
}
there s a php function for that which return a boolean.
or if you wanna check if one of the element in arrays is present in description, maybe you 'll need to iterate on them
foreach($array as element){
if(preg_match("#".$element."#", $description){
echo "found";
}
}
If your question is correctly phrased and indeed you are searching a string, you should try something like this:
function getExtractedValue($a, $description) {
$results = array();
foreach($a as $array_item) {
if (strpos($array_item, $description) !== FALSE) {
$results[] = $array_item;
}
}
return $results;
}
The function will return an array of the matched phrases from the string.
Try This..
if ( in_array ( $str , $array ) ) {
echo 'It exists'; } else {
echo 'Does not exist'; }
I've been looking for a way to check if any of an array of values exists in a string, but it seems that PHP has no native way of doing this, so I've come up with the below.
My question - is there a better way of doing this, as this seems pretty inefficient? Thanks.
$match_found = false;
$referer = wp_get_referer();
$valid_referers = array(
'dd-options',
'dd-options-footer',
'dd-options-offices'
);
/** Loop through all referers looking for a match */
foreach($valid_referers as $string) :
$referer_valid = strstr($referer, $string);
if($referer_valid !== false) :
$match_found = true;
continue;
endif;
endforeach;
/** If there were no matches, exit the function */
if(!$match_found) :
return false;
endif;
Try with following function:
function contains($input, array $referers)
{
foreach($referers as $referer) {
if (stripos($input,$referer) !== false) {
return true;
}
}
return false;
}
if ( contains($referer, $valid_referers) ) {
// contains
}
What about this:
$exists = true;
array_walk($my_array, function($item, $key) {
$exists &= (strpos($my_string, $item) !== FALSE);
});
var_dump($exists);
This will check if any of the array values exists in the string. If only one is missing, You are given a false response. Should You need to find out which one are not present in the string, try this:
$exists = true;
$not_present = array();
array_walk($my_array, function($item, $key) {
if(strpos($my_string, $item) === FALSE) {
$not_present[] = $item;
$exists &= false;
} else {
$exists &= true;
}
});
var_dump($exists);
var_dump($not_present);
First of, alternate syntax is nice to use, but historically it's used in template files. Since it's structure is easily readable while coupling/decouping the PHP interpreter to interpolate HTML data.
Second, it's generally wise if all your code does is to check something, to immediately return if that condition is met:
$match_found = false;
$referer = wp_get_referer();
$valid_referers = array(
'dd-options',
'dd-options-footer',
'dd-options-offices'
);
/** Loop through all referers looking for a match */
foreach($valid_referers as $string) :
$referer_valid = strstr($referer, $string);
if($referer_valid !== false) :
$match_found = true;
break; // break here. You already know other values will not change the outcome
endif;
endforeach;
/** If there were no matches, exit the function */
if(!$match_found) :
return false;
endif;
// if you don't do anything after this return, it's identical to doing return $match_found
Now as specified by some of the other posts in this thread. PHP has a number of functions that can help. Here's a couple more:
in_array($referer, $valid_referers);// returns true/false on match
$valid_referers = array(
'dd-options' => true,
'dd-options-footer' => true,
'dd-options-offices' => true
);// remapped to a dictionary instead of a standard array
isset($valid_referers[$referer]);// returns true/false on match
Ask if you have any questions.
1. PHP function.
I've created validating function, here it is in shorter version:
function my_function($input) {
$settings = my_source(); // function taht outputs a long array
foreach ($settings as $setting) {
$id = $setting['id'];
$foo = $setting['foo'];
$option = get_option('my_theme_settings');
if($foo == "bar") {
$valid_input[$id] = $input[$id];
}
}
return $valid_input;
};
Basically it takes $input and saves it as $valid_input. When it gets new $input it overwrites the old #valid_inpu and so on.
I want to create an additional $valid_input[$id] array that will not overwrite itself, but just push new elements inside.
2. Array_push() that doesn't work.
So the new updated code will look like that:
function my_function($input) {
$settings = my_source(); // function taht outputs a long array
foreach ($settings as $setting) {
$id = $setting['id'];
$foo = $setting['foo'];
$option = get_option('my_theme_settings');
if($foo == "bar") {
$valid_input[$id] = $input[$id];
}
else if($foo == "noupdate") { // it doesn't work
$valid_input[$id] = array();
array_push($valid_input[$id], $input[$id]);
}
}
return $valid_input;
};
As mentioned in comment above - this doesn't work, input always overwrites the option, it creates an array but it always contains only one element that is being erased with the new one (I guess array_push should prevent that behavior, right?).
3. The same happens with $array[] =
function my_function($input) {
$settings = my_source(); // function taht outputs a long array
foreach ($settings as $setting) {
$id = $setting['id'];
$foo = $setting['foo'];
$option = get_option('my_theme_settings');
if($foo == "bar") {
$valid_input[$id] = $input[$id];
}
else if($foo == "noupdate") { // it doesn't work
$valid_input[$id][] = $input[$id];
}
}
return $valid_input;
};
Still it overwrites the old value of $valid_input instead of pushing an element.
Any ideas? Maybe there's something wrong with the code? This whole function a Wordpress callback for function called register_setting(), but I guess it's mostly PHP related as folks on WPSE can't help me.
4. EDIT
This does exactly what I want, but why point 3. doesn't work then?
else if($foo == "noupdate") { // it doesn't work
$valid_input[$id][] = 'something';
$valid_input[$id][] = 'something_else';
$valid_input[$id][] = 'something_else2';
}
$valid_input[$id] needs to be set to array before you treat it as one.
$valid_input[$id] = array();
array_push( $valid_input[$id], "some stuff");
Same deal with [] notation
$valid_input[$id] = array();
$valid_input[$id][] = "some stuff";
To check if the array has been declared, so this:
if(!is_array($valid_input[$id]){
$valid_input[$id] = array();
}
The thing is that objects are passed as reference. you need to clone the objects before using the array_push function. here is a sample function that will clone an object:
function DeepCopy($ObjectToCopy) {
return unserialize(serialize($ObjectToCopy));
}
then you can use it this way
array_push($MyObjectsArray, DeepCopy($MyObject));
is it possible that you are trying to push a new value to the array with a key value that already exists? i would test for an existing key value in your array before trying to push a value/key pair to it. example:
if ( !isset( $arr[ $key ] ) ) {
$arr[ $key ] = $value;
} else {
echo " duplicate key value ";
}
Either array_push() or a variable used with the array append operator [] need to actually be an array or these won't work. Double check that whatever is in $valid_input[$id] is an array before doing array operations on the variable. Check by doing:
if (is_array($valid_input[$id])) {
// your code
}