PHP Unset Command in If Statement Not Working - php

I would like to unset an HTTP Posted key from the array after it echoes the "1" result, but the unset doesn't seem to work. How can I fix this?
$keylist = array('HHH', 'GGG');
if (in_array($_POST["keys"], $keylist)){
echo "1";
unset($keylist[$_POST["keys"]]);
} else {
echo "0" ;
}
Appreciate any help,
Hobbyist

Your unsetting $keylist not $_POST
unset($_POST["keys"]);

You're using the wrong array key for unsetting (You're trying to unset $keylist["HHH"], not, say, $keylist[0]) - you'll need to retrieve the key from the array, and then unset that specifically in order to remove it from the keylist.
$index = array_search($_POST["keys"], $keylist);
if($index!==false) { //YES, NOT DOUBLE EQUALS
unset($keylist[$index));
}
If $_POST["keys"] is an array of keys, you'll need to use array_keys with a search_value instead.
Array_search documentation: http://php.net/manual/en/function.array-search.php
Array_keys documentation: http://php.net/manual/en/function.array-keys.php
EDIT: Adding a full, working example.
<?
$_POST["keys"]="asdjkgldshglsjhgsdlhgsdlghsdlghsdlgh";
$keylist=array("asdjkgldshglsjhgsdlhgsdlghsdlghsdlgh","derp2");
if(in_array($_POST["keys"], $keylist)) {
$indexToRemove = array_search($_POST["keys"], $keylist);
echo "1";
print_r($keylist);
unset($keylist[$indexToRemove]);
print_r($keylist);
} else {
echo "0";
print_r($keylist);
}
?>
Another example, this time checking the index itself to see if it is not false:
<?
$_POST["keys"]="asdjkgldshglsjhgsdlhgsdlghsdlghsdlgh";
$keylist=array("asdjkgldshglsjhgsdlhgsdlghsdlghsdlgh","derp2");
$indexToRemove = array_search($_POST["keys"], $keylist);
if($indexToRemove!==false) {
echo "1";
print_r($keylist);
unset($keylist[$indexToRemove]);
print_r($keylist);
} else {
echo "0";
print_r($keylist);
}
?>
Output:
1Array ( [0] => asdjkgldshglsjhgsdlhgsdlghsdlghsdlgh [1] => derp2 ) Array ( [1] => derp2 )
I realize now that I only had one = on the $index!==false check - the reason you need two is because $index is 0 if you're removing the first element of an array. Per PHP documentation,
Warning
This function may return Boolean FALSE, but may also return a non-Boolean
value which evaluates to FALSE. Please read the section on Booleans for more
information. Use the === operator for testing the return value of this function.

in_array($_POST["keys"], $keylist) checks if the posted value $_POST["keys"] is present as a value in $keylist, but unset($keylist[$_POST["keys"]]) uses $_POST["keys"] as the key in $keylist to unset something.
Since in_array() returns true, the posted value is present in the array $keylist. But you can't do unset($keylist['GGG']) because that value is not set.
A simple solution is to use the same values as keys too:
$keylist = array('HHH', 'GGG');
$keylist = array_combine($keylist, $keylist);
More about array_combine().

Your array have keys. So "HHH" in keylist is $keylist[0] and not $keylist['HHH']. You can not unset it because you have to define the array key instead of the array value.
Try to search for the array value like this:
array_search($_POST["keys"], $keylist)
This will return the array key for you or false if its not found. Your full code should like look like:
echo "1";
$arrkey = array_search($_POST["keys"], $keylist);
if( $arrkey !== false ){
unset($keylist[$arrkey]);
}
Here the PHP Manual for the array_search function: http://php.net/manual/en/function.array-search.php

Related

PHP How to check if array has not key and value

I am using one custom CMS developed by someone and getting issue to check the array result.
The function returns an array of username by passing userids array.
Example Code
$all_users = "1,5,9,10,25,40"; // getting from database
$user_ids = explode(',', $all_users);
$usernames = get_userids_to_usernames($user_ids); //this returns usernames array by passing uesrids array
If the database has not users in the column than the function is returning weird empty / null array as below.
var_dump($usernames);
array(1) { [""]=> NULL }
print_r($usernames);
(
[] =>
)
Now issue is, I want to check if array is empty or has value in return but I have tried everything is_null, empty, count($usernames) > 0 but none of these working.
Can anyone please help me to check conditionally if array has value or empty like above empty result.
Here is a workaround
if (array_key_exists('', $a) && $a[''] === null) {
unset($a['']);
}
then check on emptiness
You can use in_array to check if the array has an empty value and array_key_exists to check the key.
in_array("", $array)
array_key_exists("", $array)
http://php.net/manual/en/function.in-array.php
http://php.net/manual/fr/function.array-key-exists.php
Iterate through array, and check if keys or values are empty or null
$newarray = [];
foreach($array as $key=>$value)
{
if(is_null($value) || trim($value) == '' || is_null($value) || trim($key) == ''){
continue; //skip the item
}
$newarray[$key] = $value;
}
If you want to use empty with it, try array filter
if (empty(array_filter($arr))) {
//Do something
}
Array filter will automatically remove falsey values for you, and you can include a callback should you need more flexability.

Check if a value exists in array (Laravel or Php)

I have this array:
$list_desings_ids = array('hc1wXBL7zCsdfMu','dhdsfHddfD','otheridshere');
With a die() + var_dump() this array return me:
array:2 [▼
0 => "hc1wXBL7zCsdfMu"
1 => "dhdsfHddfD"
2 => "otheridshere"
]
I want check if a design_id exists in $list_desings_ids array.
For example:
foreach($general_list_designs as $key_design=>$design) {
#$desing->desing_id return me for example: hc1wXBL7zCsdfMu
if(array_key_exists($design->design_id, $list_desings_ids))
$final_designs[] = $design;
}
But this not works to me, what is the correct way?
You can use in_array for this.
Try
$design_id = 'hc1wXBL7zCsdfMu';
$list_desings_ids = array('hc1wXBL7zCsdfMu','dhdsfHddfD','otheridshere');
if(in_array($design_id, $list_desings_ids))
{
echo "Yes, design_id: $design_id exits in array";
}
instead array_key_exists you just type in_array this will solve your issue
because if you dump your this array
$list_desings_ids = array('hc1wXBL7zCsdfMu','dhdsfHddfD','otheridshere');
output will be,
array(
0 => hc1wXBL7zCsdfMu,
1 => dhdsfHddfD,
2 => otheridshere
)
so your code array_key_exists will not work, because here in keys 0,1,2 exists, So, you want to check values,so for values, just do this in_array it will search for your desire value in your mentioned/created array
you need to change only your condition replace with that code
if(in_array($design->design_id, $list_desings_ids))
Your array not have key .
try this
foreach($general_list_designs as $key_design=>$design) {
#$desing->desing_id return me for example: hc1wXBL7zCsdfMu
if(in_array($design->design_id, $list_desings_ids))
$final_designs[] = $design;
}
use Illuminate\Support\Collection;
First import above class then write below code
$list = new Collection(['hc1wXBL7zCsdfMu', 'dhdsfHddfD', 'otheridshere']);
$id = 'hc1wXBL7zCsdfMu';
if ($list->contains($id)) {
//yes: $id exits in array
}

Unset value (with unknown index) from array without iterating

I want to unset a known value from an array. I could iterate with a for loop to look for the coincident value and then unset it.
<?php
for($i=0, $length=count($array); $i<$length; $i++)
{
if( $array[$i] === $valueToUnset )
//unset the value from the array
}
Any idea? Any way to achieve it without looping?
I am presuming that your intention is to get the index back, as you already have the value. I am further presuming that there is also a possibility that said value will NOT be in the array, and we have to account for that. I am not sure what you are using array_slice for. So, if I properly understand your requirements, a simple solution would be as follows:
<?php
$foundIndex = false; //Initialize variable that will hold index value
$foundIndex = array_search($valueToExtract, $array);
if($foundIndex === null) {
//Value was not found in the array
} else {
unset($array[$foundIndex]; //Unset the target element
}
?>
array_diff is the solution:
<?php
array_diff($array, array($valueToUnset));
No iteration needed.

Check if a specific word is in an array

I am having a a bit of an issue related to checking a returned array for specific matches.
Here is what I do:
I query a server API and the API returns a printable result using:
print_r($result);
the printed result is:
Array
(
[<html><center>Password_Saved!</center></html>] =>
)
So I thought I could do something like:
function checkResult ($needle, $haystack) { return ( stripos($haystack,$needle) !== false ? TRUE : FALSE); }
if ((checkResult("saved",$result))) {
echo "saved";
} else {
echo "not saved";
}
However, this does not work at all, so I am wondering if you could help me find a way if the $result contains the string saved since I need to know this to perform the next action based on the result.
Your help would be greatly appreciated.
The value you are looking for exists in the array's key instead of value.
As such, you need to be doing your search in the array's keys instead of values.
foreach ($result as $key => $value)
{
if (false !== stripos ($key, "saved"))
{
print "{$key} => Saved";
}
}
it doesn't work because your searching for saved when the value you have in the string is Saved. and you should pass your array key.
if ((checkResult("Saved",array_keys($result)[0]))) {
echo "saved";
} else {
echo "not saved";
}
Read about php preg_grep function
For example:
$needle_pattern = '/search/i'; // i for case insensitive
preg_grep($needle_pattern, $array_haystack);
Also notice that in your code you're mixing "saved" and "Saved" which are different :)
For further reading about this method:
How to search in an array with preg_match?
P.S If your "haystack" is actually the keys, you can switch $array_haystack with array_keys($array_haystack) to get an array of all keys.

PHP array_search not working

can anybody let me know why array_search doesnt works for me? All i want is to search value and and get corresponding key value
for eg if i search wiliam i should get 4.. Its simple but aint working for me
<?php
$fqlResult[0]['uid']='1';
$fqlResult[0]['name']='Jay';
$fqlResult[1]['uid']='2';
$fqlResult[1]['name']='UserName2';
$fqlResult[2]['uid']='3';
$fqlResult[2]['name']='Frances';
$fqlResult[3]['uid']='4';
$fqlResult[3]['name']='William';
for($i=0;$i<count($fqlResult);$i++)
{
$userdbname="'".$fqlResult[$i]['name']."'";
$userdb[$userdbname]="'".$fqlResult[$i]['uid']."'";
}
echo "<pre>";
print_r($userdb);
echo "</pre>";
echo array_search('4', $userdb);
?>
It doesn't work because array_seach searches values and "William" is a key. To complicate things, your values and keys are wrapped in single quotes during the for loop.
You'd want to do something like this:
if ( ! empty($userdb["'William'"]) )
{
// Echoes "'4'"
echo $userdb["'William'"];
}
// To find user ID "'4'"
// Outputs "'William'"
echo array_search("'4'", $userdb);
If you don't want things wrapped in single quotes, you'll need to change your for loop as follows:
for($i=0;$i<count($fqlResult);$i++)
{
$userdbname=$fqlResult[$i]['name'];
$userdb[$userdbname]=$fqlResult[$i]['uid'];
}
if ( ! empty($userdb["William"]) )
{
// Outputs "4" (without the single quotes)
echo $userdb["William"];
}
// To find user ID "4" (without the single quotes)
// Outputs "William"
echo array_search('4', $userdb);
array_search() searches values, not keys.
If you want to check the existence of something that you use as a key in an array, you can just use isset:
if(isset($userdb['William'])) {
echo "$userdb[William] is William's uid!";
}
for($i=0;$i<count($fqlResult);$i++)
{
$userdbname=$fqlResult[$i]['uid'];
$userdb[$userdbname]=$fqlResult[$i]['name'];
}
Change
$userdb[$userdbname]="'".$fqlResult[$i]['uid']."'";
with this
$userdb[$i] = "{$fqlResult[$i]['name']}";
array_search only works with arrays of scalar data. You're trying to search an array of arrays. You can easily search the array yourself:
function search_array_col($array, $col, $val)
{
foreach ($array as $key => $a)
{
if ($a[$col] == $val) return $key;
}
return null;
}
echo search_array_col($fqlResult, 'name', 'William') , "\n";
echo search_array_col($fqlResult, 'uid', '4') , "\n";
Edit: n/m, I misread your code. However, you could still use this to search your original array, so I'll leave the answer for reference.
try this:
foreach($fqlResult as $result)
{
$name = $result["name"];
$uid = $result["uid"];
$userdb[$name] = $uid;
}
then you want to use array_key_exists() to find the key. array_search() only works for searching values, not keys.
$nameExists = array_key_exists("William",$userdb);
You can remove the quotes in the $userdbname="'".$fqlResult[$i]['name']."'";
rewrite it to
$userdbname= $fqlResult[$i]['name'];

Categories