Check if element exists in PHP array - php

I have an array which is given below:
array(1) { [0]=> array(1) { ["type"]=> string(4) "item" } }
I'm using to the following code in an if statement to see if "item" exists in the array but it isn't been evaluated as true
if (array_key_exists('item', $_SESSION['type']))
{
//do something
}
What am I doing wrong?

array_key_exists checks the keys of the array, not the values; "item" is a value.
To check for the existence of values use either in_array (if you don't care about the key in case the item is found) or array_search (if you want to know what the key for that item was). For example:
if (in_array("item", $_SESSION['type'])) // do something

Its array in array. And function array_key_exists checks only one level deep, if the key exists. And your ked is 2 levels deep, so it cant return true, because there is key only "0".
And "item" is not key, but value; you have to use function in_array or array_search.
And also you should create your own function for that, because its array in array...

You need to use in_array to find if an element exists in an array.
array_key_exists checks if the key of the array is present or not

Related

How to find the desired element in the array and check whether it has a value or not?

I have a big array like this:
"twitter_link" => "http://twitter.com"
"twitter_text" => "text"
"youtube_link" => ""
"youtube_text" => ""
"snapchat_link" => "http://twitter.com"
"snapchat_text" => "text"
"linkedin_link" => ""
"linkedin_text" => ""
In this array, I need to find all all *_link keys and check if the value is set, then add all the keys where there is a value to another array
I would like to recommend you to read the following docs: https://laravel.com/docs/8.x/collections#available-methods, this may help you to find a multiple ways to iterate and alter an array if you don't think the array_* methods from php are enough for your needs! :D
Answering your question, what you need here is the knowledge of:
preg_match(...) function
array_filter(...) function using the flag: ARRAY_FILTER_USE_BOTH
You simply have to do the following:
$result = array_filter($links, fn($v, $k) => ($v !== "" && preg_match("/(_link)+$/i", $k)), ARRAY_FILTER_USE_BOTH)
And voilá, but what's the explanation? Simply...
Filter will use key and value for filtering by passing the flag ARRAY_FILTER_USE_BOTH as third element on array_filter() method.
On the filtering process, the $v (or value) shouldn't be empty.
Also on the filtering process, the $k (or key) should have a _filter at the end of the string.

Custom fields in array not posting when containing numbers

I have a PHP form where I need to search custom fields. If the custom field contains a number, it won't show as posted, however a string of letters will.
If I var_dump($_POST['customfield']) it displays the field, key and value. I attempted a foreach loop to count how many fields post. It returns 0 if I only post with numbers.
$postCustomFields = $_POST['customfield'];
foreach ($postCustomFields as $key => $cfield) {
if ($postCustomFields[$key][$cfield] != null) {
$customfields++;
}
}
Fields are named customfield[0]. Inside the brackets is the field ID. I just need a way to have the numeric value be usable and count in the customfields array.
var_dump($_POST['customfield']) output. The key is the field ID:
array(9) {
[3]=>
string(1) "5"
}
Thanks
You are confused with array reference. You have array with array [key => value], but you try to access data like array[key][value] and there are not exists.
In your case your $postCustomFields[$key] will contains your ID 5

How to know if input array elements are empty? [duplicate]

This question already has answers here:
Checking if all the array items are empty PHP
(7 answers)
Is there a way to check if all the elements in an array are null in php
(5 answers)
Closed 4 years ago.
I have an input wich is an array, the key of the array is the lang id like this
<input type="text" name="name[{{ $lang->id }}]">
this field is optional, so i don't whant to validate if it is or not, what i want is to check if both element of the array are empty do something. Lets supose this is the input name[]
{
"1": null,
"2": null
}
i can't do
if($request->has('name')) {
//do something
}else {
//do another thing
}
Because the $request has a name, is there a way to do something like this
if(array_is_empty($request->has('name'))) {
//do something
}else {
//do another thing
}
$imply use array filter which will remove any empty or falsey items from the array, then check if anything is left:
if(empty(array_filter($array)))
If you want to consider spaces empty, for example someone just puts blank space in the field you can throw in an array map with trim as the callback, like this:
if(empty(array_filter(array_map('trim',$array))))
Test It
$a = [
"1" => null,
"2" => null
];
if(empty(array_filter($a))) echo 'empty';
Output
empty
Sandbox
array_filter — Filters elements of an array using a callback function
Iterates over each value in the array passing them to the callback function. If the callback function returns true, the current value from array is returned into the result array. Array keys are preserved.
PHP will consider several things as falsy and remove them, you can supply your own callback if you need finer control, but some of things considered falsy
0
"0"
""
false
null
[] //this is what you get after filtering $array
There may be others, but this should give you the idea.
Because array filter returns an empty array [] which is also falsy you can even just do this if you don't want to call empty
if(!array_filter($array))
But it makes the code a bit less readable because it depends on PHP's loose typing where when empty is used the intent is crystal clear.
The Laravel validator has an nullable rule for validation on fields that are optional.
https://laravel.com/docs/5.6/validation#a-note-on-optional-fields
And can validate arrays.
https://laravel.com/docs/5.6/validation#validating-arrays
So you might do...
$request->validate([
'name.*' => 'nullable|string',
]);

How to delete array element by index

Is there any possible way to delete element from array? It is shopping cart storing item IDs. I want to make delete function.
For example - cart_handler.php?delete=2687
array(5) { [1967]=> float(1) [1966]=> float(1) [2233]=> float(5) [2687]=> float(1) [2081]=> float(4) }
Yes you can, the easiest way would be to search for the item ID in the array, and then unset the key associated with it -- and then as an extension you could re-base the array to fix the array keys. Please Note: I haven't put any validation on the $arrayKey and what it returns, you should ensure that the array_search function is returning as expected before unsetting the array key just to be safe.
So something like this:
$data = [1967, 1966, 2233, 2687, 2081];
$arrayKey = array_search(1966, $data);
unset($data[$arrayKey]);
The specified product ID would be unset by that, just replace 1966 with your $_GET variable. i.e.
array_search($_GET['delete'], $data)
And the $data array would be a list of all your valid product IDs, that you could pull out from your database, or wherever you are storing them.
If you want to re-base the key indexes after this you can do:
$data = array_values($data);
What the above does is fixes the array key indexes, when you unset an element it will be removed from the array, but all keys will maintain their current indexes. So the array indexes may progress like so: 0, 1, 3, 4. If you re-base the array with the above they'll progress naturally again: 0, 1, 2, 3.
Hope that helps, any questions just let me know.

php determine position of array key relative to another key

I was wondering if it was possible to determine what position a key in an array is in relation to another key. I have a large multidimensional array and I need perform Function A when the key [E14_21] comes before [E14_20] and I need to perform a different Function B if not...
//perform Function A if:
[E14_20_0] => Array
(
[E14_21] => 3235
[E14_20] => 96
)
//Perform Function B if:
[E14_20_0] => Array
(
[E14_20] => 96
[E14_21] => 3235
)
You can do something like:
$keys = array_keys($E14_20_0);
if(array_search("E14_21", $keys) < array_search("E14_20", $keys)) {
// function A
} else {
// function B
}
You will of course need to add some sanity checks to make sure both keys exist in the array, etc.
It seems you might do this:
reset($E14_20_0);
first = each($E14_20_0);
second = each($E14_20_0);
if(first['key'] > second['key'])
{
//do something
}
This is very specific to your example, but it might help you get started.
reset() will reset the array pointer to the "first" element. each() returns the key and value of the array based on the pointer and advances the pointer. Then you can compare keys and perform your logic.

Categories