PHP create an array with values that equal true - php

I have passed a series of parameters from a jQuery file to a PHP script for processing.
Some of the parameters include names, email, department, etc. The majority of the parameters will either be TRUE or FALSE.
I want to build an array to include all of the parameters that equal TRUE.
<?php
$value = $_POST['criteria'];
$firstname = $value['firstname'];
$email = $value['email'];
$department = $value['department'];
$parameter1 = $value['parameter1']; // equals TRUE
$parameter2 = $value['parameter2']; // equals FALSE
$parameter3 = $value['parameter3']; // equals TRUE
$parameter4 = $value['parameter4']; // equals TRUE
?>
So the results of the array I want to produce should look like this:
$array = ['parameter1', 'parameter3', 'parameter4'];
I know I must use a loop, but I am not exactly sure how to start it.
Edit
Here is where I create the variable criteria in jQuery, starting with a button click event:
$('#requestAppSubmit').on('click', function()
{
var criteria =
{
firstname: $('#firstname').val(),
email: $('#email').val(),
department: $('#department').val(),
// the next parameters check if a checkbox was checked
parameter1: $('#dashboard').is(':checked'),
parameter2: $('#schedules').is(':checked'),
parameter3: $('#finance').is(':checked'),
parameter4: $('#businessplan').is(':checked'),
// quite a few more parameters
}
// then I use a ajax post
$.post('process/editRep.php', {criteria:criteria}, function(data)
{
console.log(data);
//
});
});
At this point, using your suggestions below, the most I can output is this:
Array()

You can use array_filter() to keep only boolean values, and then, use array_keys() to get the names:
$value = [
'firstname'=>'foo',
'email'=>'bar',
'department'=>'baz',
'parameter1'=>true,
'parameter2'=>false,
'parameter3'=>true,
'parameter4'=>true
];
$array = array_filter($value, function($item) {
return $item === true;
});
$array = array_keys($array);
print_r($array);
Output:
Array
(
[0] => parameter1
[1] => parameter3
[2] => parameter4
)
If values are not booleans, you could also use :
$array = array_filter($value, function($item) {
return is_numeric($item) && $item == true;
});
This will work with '0' and '1'.

You don't need a loop at all, just two functions: array_filter to filter out the false values, and array_keys to get the keys:
$array = array_keys(array_filter($values));
// results = ['parameter1', 'parameter3', 'parameter4']

Using foreach:
foreach($value as $index => $bool){
if($bool){
$new_array[] = $index;
}
}
Will only work if your values are of bool type and not string
If they are strings just compare them using ==

I can guess from your question that you need to process a list of parameters you care what their contents are like name, department and email, as well as a boolean list of attributes, in the same POST request.
I would encapsulate all the boolean attributes you need to pass in an array:
<input type="checkbox" name="options[parameter1]"/>
<input type="checkbox" name="options[parameter2]"/>
...
and process it in PHP:
<?php
$options = $_POST['options'] ?? [];
$onlyTrueOptions = array();
foreach($options as $optionName => $value) {
if($value) // or another desidered comparison
$onlyTrueOptions[] = $optionName;
}

Never, really never use "static-incremented" variables. That's what you use arrays for.
$arr = array();
for($i = 1; $i<=4; $i++)
{
if(strcmp($value['parameter'.$i],"TRUE") === 0)
{
array_push($arr,"parameter$i");
}
}

Related

PHP - How to check for multiple array keys in $_POST variable [duplicate]

I have a variety of arrays that will either contain
story & message
or just
story
How would I check to see if an array contains both story and message? array_key_exists() only looks for that single key in the array.
Is there a way to do this?
Here is a solution that's scalable, even if you want to check for a large number of keys:
<?php
// The values in this arrays contains the names of the indexes (keys)
// that should exist in the data array
$required = array('key1', 'key2', 'key3');
$data = array(
'key1' => 10,
'key2' => 20,
'key3' => 30,
'key4' => 40,
);
if (count(array_intersect_key(array_flip($required), $data)) === count($required)) {
// All required keys exist!
}
If you only have 2 keys to check (like in the original question), it's probably easy enough to just call array_key_exists() twice to check if the keys exists.
if (array_key_exists("story", $arr) && array_key_exists("message", $arr)) {
// Both keys exist.
}
However this obviously doesn't scale up well to many keys. In that situation a custom function would help.
function array_keys_exists(array $keys, array $arr) {
return !array_diff_key(array_flip($keys), $arr);
}
Surprisingly array_keys_exist doesn't exist?! In the interim that leaves some space to figure out a single line expression for this common task. I'm thinking of a shell script or another small program.
Note: each of the following solutions use concise […] array declaration syntax available in php 5.4+
array_diff + array_keys
if (0 === count(array_diff(['story', 'message', '…'], array_keys($source)))) {
// all keys found
} else {
// not all
}
(hat tip to Kim Stacks)
This approach is the most brief I've found. array_diff() returns an array of items present in argument 1 not present in argument2. Therefore an empty array indicates all keys were found. In php 5.5 you could simplify 0 === count(…) to be simply empty(…).
array_reduce + unset
if (0 === count(array_reduce(array_keys($source),
function($in, $key){ unset($in[array_search($key, $in)]); return $in; },
['story', 'message', '…'])))
{
// all keys found
} else {
// not all
}
Harder to read, easy to change. array_reduce() uses a callback to iterate over an array to arrive at a value. By feeding the keys we're interested in the $initial value of $in and then removing keys found in source we can expect to end with 0 elements if all keys were found.
The construction is easy to modify since the keys we're interested in fit nicely on the bottom line.
array_filter & in_array
if (2 === count(array_filter(array_keys($source), function($key) {
return in_array($key, ['story', 'message']); }
)))
{
// all keys found
} else {
// not all
}
Simpler to write than the array_reduce solution but slightly tricker to edit. array_filter is also an iterative callback that allows you to create a filtered array by returning true (copy item to new array) or false (don't copy) in the callback. The gotchya is that you must change 2 to the number of items you expect.
This can be made more durable but verge's on preposterous readability:
$find = ['story', 'message'];
if (count($find) === count(array_filter(array_keys($source), function($key) use ($find) { return in_array($key, $find); })))
{
// all keys found
} else {
// not all
}
One more possible solution:
if (!array_diff(['story', 'message'], array_keys($array))) {
// OK: all the keys are in $array
} else {
// FAIL: some keys are not
}
It seems to me, that the easiest method by far would be this:
$required = array('a','b','c','d');
$values = array(
'a' => '1',
'b' => '2'
);
$missing = array_diff_key(array_flip($required), $values);
Prints:
Array(
[c] => 2
[d] => 3
)
This also allows to check which keys are missing exactly. This might be useful for error handling.
The above solutions are clever, but unnecessarily slow. A simple foreach loop over a few keys is much faster.
function array_keys_exist($keys, $array){
foreach($keys as $key){
if(!array_key_exists($key, $array)) {
return false;
}
}
return true;
}
If you have something like this:
$stuff = array();
$stuff[0] = array('story' => 'A story', 'message' => 'in a bottle');
$stuff[1] = array('story' => 'Foo');
You could simply count():
foreach ($stuff as $value) {
if (count($value) == 2) {
// story and message
} else {
// only story
}
}
This only works if you know for sure that you ONLY have these array keys, and nothing else.
Using array_key_exists() only supports checking one key at a time, so you will need to check both seperately:
foreach ($stuff as $value) {
if (array_key_exists('story', $value) && array_key_exists('message', $value) {
// story and message
} else {
// either one or both keys missing
}
}
array_key_exists() returns true if the key is present in the array, but it is a real function and a lot to type. The language construct isset() will almost do the same, except if the tested value is NULL:
foreach ($stuff as $value) {
if (isset($value['story']) && isset($value['message']) {
// story and message
} else {
// either one or both keys missing
}
}
Additionally isset allows to check multiple variables at once:
foreach ($stuff as $value) {
if (isset($value['story'], $value['message']) {
// story and message
} else {
// either one or both keys missing
}
}
Now, to optimize the test for stuff that is set, you'd better use this "if":
foreach ($stuff as $value) {
if (isset($value['story']) {
if (isset($value['message']) {
// story and message
} else {
// only story
}
} else {
// No story - but message not checked
}
}
What about this:
isset($arr['key1'], $arr['key2'])
only return true if both are not null
if is null, key is not in array
I use something like this quite often
$wantedKeys = ['story', 'message'];
$hasWantedKeys = count(array_intersect(array_keys($source), $wantedKeys)) > 0
or to find the values for the wanted keys
$wantedValues = array_intersect_key($source, array_fill_keys($wantedKeys, 1))
try this
$required=['a','b'];$data=['a'=>1,'b'=>2];
if(count(array_intersect($required,array_keys($data))>0){
//a key or all keys in required exist in data
}else{
//no keys found
}
This is the function I wrote for myself to use within a class.
<?php
/**
* Check the keys of an array against a list of values. Returns true if all values in the list
is not in the array as a key. Returns false otherwise.
*
* #param $array Associative array with keys and values
* #param $mustHaveKeys Array whose values contain the keys that MUST exist in $array
* #param &$missingKeys Array. Pass by reference. An array of the missing keys in $array as string values.
* #return Boolean. Return true only if all the values in $mustHaveKeys appear in $array as keys.
*/
function checkIfKeysExist($array, $mustHaveKeys, &$missingKeys = array()) {
// extract the keys of $array as an array
$keys = array_keys($array);
// ensure the keys we look for are unique
$mustHaveKeys = array_unique($mustHaveKeys);
// $missingKeys = $mustHaveKeys - $keys
// we expect $missingKeys to be empty if all goes well
$missingKeys = array_diff($mustHaveKeys, $keys);
return empty($missingKeys);
}
$arrayHasStoryAsKey = array('story' => 'some value', 'some other key' => 'some other value');
$arrayHasMessageAsKey = array('message' => 'some value', 'some other key' => 'some other value');
$arrayHasStoryMessageAsKey = array('story' => 'some value', 'message' => 'some value','some other key' => 'some other value');
$arrayHasNone = array('xxx' => 'some value', 'some other key' => 'some other value');
$keys = array('story', 'message');
if (checkIfKeysExist($arrayHasStoryAsKey, $keys)) { // return false
echo "arrayHasStoryAsKey has all the keys<br />";
} else {
echo "arrayHasStoryAsKey does NOT have all the keys<br />";
}
if (checkIfKeysExist($arrayHasMessageAsKey, $keys)) { // return false
echo "arrayHasMessageAsKey has all the keys<br />";
} else {
echo "arrayHasMessageAsKey does NOT have all the keys<br />";
}
if (checkIfKeysExist($arrayHasStoryMessageAsKey, $keys)) { // return false
echo "arrayHasStoryMessageAsKey has all the keys<br />";
} else {
echo "arrayHasStoryMessageAsKey does NOT have all the keys<br />";
}
if (checkIfKeysExist($arrayHasNone, $keys)) { // return false
echo "arrayHasNone has all the keys<br />";
} else {
echo "arrayHasNone does NOT have all the keys<br />";
}
I am assuming you need to check for multiple keys ALL EXIST in an array. If you are looking for a match of at least one key, let me know so I can provide another function.
Codepad here http://codepad.viper-7.com/AKVPCH
Hope this helps:
function array_keys_exist($searchForKeys = array(), $inArray = array()) {
$inArrayKeys = array_keys($inArray);
return count(array_intersect($searchForKeys, $inArrayKeys)) == count($searchForKeys);
}
This is old and will probably get buried, but this is my attempt.
I had an issue similar to #Ryan. In some cases, I needed to only check if at least 1 key was in an array, and in some cases, all needed to be present.
So I wrote this function:
/**
* A key check of an array of keys
* #param array $keys_to_check An array of keys to check
* #param array $array_to_check The array to check against
* #param bool $strict Checks that all $keys_to_check are in $array_to_check | Default: false
* #return bool
*/
function array_keys_exist(array $keys_to_check, array $array_to_check, $strict = false) {
// Results to pass back //
$results = false;
// If all keys are expected //
if ($strict) {
// Strict check //
// Keys to check count //
$ktc = count($keys_to_check);
// Array to check count //
$atc = count(array_intersect($keys_to_check, array_keys($array_to_check)));
// Compare all //
if ($ktc === $atc) {
$results = true;
}
} else {
// Loose check - to see if some keys exist //
// Loop through all keys to check //
foreach ($keys_to_check as $ktc) {
// Check if key exists in array to check //
if (array_key_exists($ktc, $array_to_check)) {
$results = true;
// We found at least one, break loop //
break;
}
}
}
return $results;
}
This was a lot easier than having to write multiple || and && blocks.
$colsRequired = ["apple", "orange", "banana", "grapes"];
$data = ["apple"=>"some text", "orange"=>"some text"];
$presentInBoth = array_intersect($colsRequired,array_keys($data));
if( count($presentInBoth) != count($colsRequired))
echo "Missing keys :" . join(",",array_diff($colsRequired,$presentInBoth));
else
echo "All Required cols are present";
Does this not work?
array_key_exists('story', $myarray) && array_key_exists('message', $myarray)
<?php
function check_keys_exists($keys_str = "", $arr = array()){
$return = false;
if($keys_str != "" and !empty($arr)){
$keys = explode(',', $keys_str);
if(!empty($keys)){
foreach($keys as $key){
$return = array_key_exists($key, $arr);
if($return == false){
break;
}
}
}
}
return $return;
}
//run demo
$key = 'a,b,c';
$array = array('a'=>'aaaa','b'=>'ccc','c'=>'eeeee');
var_dump( check_keys_exists($key, $array));
I am not sure, if it is bad idea but I use very simple foreach loop to check multiple array key.
// get post attachment source url
$image = wp_get_attachment_image_src(get_post_thumbnail_id($post_id), 'single-post-thumbnail');
// read exif data
$tech_info = exif_read_data($image[0]);
// set require keys
$keys = array('Make', 'Model');
// run loop to add post metas foreach key
foreach ($keys as $key => $value)
{
if (array_key_exists($value, $tech_info))
{
// add/update post meta
update_post_meta($post_id, MPC_PREFIX . $value, $tech_info[$value]);
}
}
$myArray = array('key1' => '', 'key2' => '');
$keys = array('key1', 'key2', 'key3');
$keyExists = count(array_intersect($keys, array_keys($myArray)));
Will return true, because there are keys from $keys array in $myArray
Something as this could be used
//Say given this array
$array_in_use2 = ['hay' => 'come', 'message' => 'no', 'story' => 'yes'];
//This gives either true or false if story and message is there
count(array_intersect(['story', 'message'], array_keys($array_in_use2))) === 2;
Note the check against 2, if the values you want to search is different you can change.
This solution may not be efficient, but it works!
Updates
In one fat function:
/**
* Like php array_key_exists, this instead search if (one or more) keys exists in the array
* #param array $needles - keys to look for in the array
* #param array $haystack - the <b>Associative</b> array to search
* #param bool $all - [Optional] if false then checks if some keys are found
* #return bool true if the needles are found else false. <br>
* Note: if hastack is multidimentional only the first layer is checked<br>,
* the needles should <b>not be<b> an associative array else it returns false<br>
* The array to search must be associative array too else false may be returned
*/
function array_keys_exists($needles, $haystack, $all = true)
{
$size = count($needles);
if($all) return count(array_intersect($needles, array_keys($haystack))) === $size;
return !empty(array_intersect($needles, array_keys($haystack)));
}
So for example with this:
$array_in_use2 = ['hay' => 'come', 'message' => 'no', 'story' => 'yes'];
//One of them exists --> true
$one_or_more_exists = array_keys_exists(['story', 'message'], $array_in_use2, false);
//all of them exists --> true
$all_exists = array_keys_exists(['story', 'message'], $array_in_use2);
Hope this helps :)
I usually use a function to validate my post and it is an answer for this question too so let me post it.
to call my function I will use the 2 array like this
validatePost(['username', 'password', 'any other field'], $_POST))
then my function will look like this
function validatePost($requiredFields, $post)
{
$validation = [];
foreach($requiredFields as $required => $key)
{
if(!array_key_exists($key, $post))
{
$validation['required'][] = $key;
}
}
return $validation;
}
this will output this
"required": [
"username",
"password",
"any other field"
]
so what this function does is validate and return all the missing fields of the post request.
// sample data
$requiredKeys = ['key1', 'key2', 'key3'];
$arrayToValidate = ['key1' => 1, 'key2' => 2, 'key3' => 3];
function keysExist(array $requiredKeys, array $arrayToValidate) {
if ($requiredKeys === array_keys($arrayToValidate)) {
return true;
}
return false;
}

Using variable to access multidimensional $_POST

Consider this code:
$var = 'test';
$_POST[$test]; // equals $_POST['test']
How can I access with the same method this variable:
$_POST['test'][0];
$var = 'test[0]'; clearly doesn't work.
EDIT
Let me give a bit more information. I've got a class that builds a form.
An element is added like this:
//$form->set_element(type, name, defaultValue);
$form->set_element('text', 'tools', 'defaultValue');
This results into :
<input type="text" name="tools" value="defaultValue" />
In my class I set the value: if the form is posted, use that value, if not, use the default:
private function set_value( $name, $value='' ) {
if( $_SERVER['REQUEST_METHOD'] == 'POST' )
return $_POST[$name];
else
return $value;
}
When I want to add multiple "tools", I would like to use:
$form->set_element('text', 'tools[0]', 'defaultValue');
$form->set_element('text', 'tools[1]', 'defaultValue');
$form->set_element('text', 'tools[2]', 'defaultValue');
But in the set_value function
that gives $_POST['tools[0]'] instead of $_POST['tools'][0]
Use any number of variables in [] to access what you need:
$test = 'test';
$index = 0;
var_dump($_POST[$test][$index]);
$test = 'test';
$index = 0;
$subkey = 'key'
var_dump($_POST[$test][$index][$subkey]);
And so on.
There's no special function to achieve what you want, so you should write something, for example:
$key = 'test[0]';
$base = strstr($key, '[', true); // returns `test`
$ob_pos = strpos($key, '[');
$cb_pos = strpos($key, ']');
$index = substr($key, $ob_pos + 1, $cb_pos - $ob_pos - 1);
var_dump($arr[$base][$index]);
Edit by LinkinTED
$key = 'test[0]';
$base = $n = substr($name, 0, strpos($key, '[') );
preg_match_all('/\[([^\]]*)\]/', $key, $parts);
var_dump($arr[$base][$parts[1][0]]);
See how when you did $_POST['test'][0]; you just added [0] to the end? As a separate reference.
You have to do that.
$_POST[$test][0];
If you need both parts in variables then you need to use multiple variables, or an array.
$var = Array( "test", "0" );
$_POST[$test[0]][$test[1]];
Each dimension of an array is called by specifying the key or index together with the array variable.
You can reference a 3 dimensional array's element by mentioning the 3 indexes of the array.
$value = $array['index']['index']['index'];
Like,
$billno = $array['customers']['history']['billno'];
You can also use variables which has the index values that can be used while specifying the array index.
$var1 = 'customers';
$var2 = 'history';
$var3 = 'billno';
$billno = $array[$var1][$var2][$var3];

How to check if multiple array keys exists

I have a variety of arrays that will either contain
story & message
or just
story
How would I check to see if an array contains both story and message? array_key_exists() only looks for that single key in the array.
Is there a way to do this?
Here is a solution that's scalable, even if you want to check for a large number of keys:
<?php
// The values in this arrays contains the names of the indexes (keys)
// that should exist in the data array
$required = array('key1', 'key2', 'key3');
$data = array(
'key1' => 10,
'key2' => 20,
'key3' => 30,
'key4' => 40,
);
if (count(array_intersect_key(array_flip($required), $data)) === count($required)) {
// All required keys exist!
}
If you only have 2 keys to check (like in the original question), it's probably easy enough to just call array_key_exists() twice to check if the keys exists.
if (array_key_exists("story", $arr) && array_key_exists("message", $arr)) {
// Both keys exist.
}
However this obviously doesn't scale up well to many keys. In that situation a custom function would help.
function array_keys_exists(array $keys, array $arr) {
return !array_diff_key(array_flip($keys), $arr);
}
Surprisingly array_keys_exist doesn't exist?! In the interim that leaves some space to figure out a single line expression for this common task. I'm thinking of a shell script or another small program.
Note: each of the following solutions use concise […] array declaration syntax available in php 5.4+
array_diff + array_keys
if (0 === count(array_diff(['story', 'message', '…'], array_keys($source)))) {
// all keys found
} else {
// not all
}
(hat tip to Kim Stacks)
This approach is the most brief I've found. array_diff() returns an array of items present in argument 1 not present in argument2. Therefore an empty array indicates all keys were found. In php 5.5 you could simplify 0 === count(…) to be simply empty(…).
array_reduce + unset
if (0 === count(array_reduce(array_keys($source),
function($in, $key){ unset($in[array_search($key, $in)]); return $in; },
['story', 'message', '…'])))
{
// all keys found
} else {
// not all
}
Harder to read, easy to change. array_reduce() uses a callback to iterate over an array to arrive at a value. By feeding the keys we're interested in the $initial value of $in and then removing keys found in source we can expect to end with 0 elements if all keys were found.
The construction is easy to modify since the keys we're interested in fit nicely on the bottom line.
array_filter & in_array
if (2 === count(array_filter(array_keys($source), function($key) {
return in_array($key, ['story', 'message']); }
)))
{
// all keys found
} else {
// not all
}
Simpler to write than the array_reduce solution but slightly tricker to edit. array_filter is also an iterative callback that allows you to create a filtered array by returning true (copy item to new array) or false (don't copy) in the callback. The gotchya is that you must change 2 to the number of items you expect.
This can be made more durable but verge's on preposterous readability:
$find = ['story', 'message'];
if (count($find) === count(array_filter(array_keys($source), function($key) use ($find) { return in_array($key, $find); })))
{
// all keys found
} else {
// not all
}
One more possible solution:
if (!array_diff(['story', 'message'], array_keys($array))) {
// OK: all the keys are in $array
} else {
// FAIL: some keys are not
}
It seems to me, that the easiest method by far would be this:
$required = array('a','b','c','d');
$values = array(
'a' => '1',
'b' => '2'
);
$missing = array_diff_key(array_flip($required), $values);
Prints:
Array(
[c] => 2
[d] => 3
)
This also allows to check which keys are missing exactly. This might be useful for error handling.
The above solutions are clever, but unnecessarily slow. A simple foreach loop over a few keys is much faster.
function array_keys_exist($keys, $array){
foreach($keys as $key){
if(!array_key_exists($key, $array)) {
return false;
}
}
return true;
}
If you have something like this:
$stuff = array();
$stuff[0] = array('story' => 'A story', 'message' => 'in a bottle');
$stuff[1] = array('story' => 'Foo');
You could simply count():
foreach ($stuff as $value) {
if (count($value) == 2) {
// story and message
} else {
// only story
}
}
This only works if you know for sure that you ONLY have these array keys, and nothing else.
Using array_key_exists() only supports checking one key at a time, so you will need to check both seperately:
foreach ($stuff as $value) {
if (array_key_exists('story', $value) && array_key_exists('message', $value) {
// story and message
} else {
// either one or both keys missing
}
}
array_key_exists() returns true if the key is present in the array, but it is a real function and a lot to type. The language construct isset() will almost do the same, except if the tested value is NULL:
foreach ($stuff as $value) {
if (isset($value['story']) && isset($value['message']) {
// story and message
} else {
// either one or both keys missing
}
}
Additionally isset allows to check multiple variables at once:
foreach ($stuff as $value) {
if (isset($value['story'], $value['message']) {
// story and message
} else {
// either one or both keys missing
}
}
Now, to optimize the test for stuff that is set, you'd better use this "if":
foreach ($stuff as $value) {
if (isset($value['story']) {
if (isset($value['message']) {
// story and message
} else {
// only story
}
} else {
// No story - but message not checked
}
}
What about this:
isset($arr['key1'], $arr['key2'])
only return true if both are not null
if is null, key is not in array
I use something like this quite often
$wantedKeys = ['story', 'message'];
$hasWantedKeys = count(array_intersect(array_keys($source), $wantedKeys)) > 0
or to find the values for the wanted keys
$wantedValues = array_intersect_key($source, array_fill_keys($wantedKeys, 1))
try this
$required=['a','b'];$data=['a'=>1,'b'=>2];
if(count(array_intersect($required,array_keys($data))>0){
//a key or all keys in required exist in data
}else{
//no keys found
}
This is the function I wrote for myself to use within a class.
<?php
/**
* Check the keys of an array against a list of values. Returns true if all values in the list
is not in the array as a key. Returns false otherwise.
*
* #param $array Associative array with keys and values
* #param $mustHaveKeys Array whose values contain the keys that MUST exist in $array
* #param &$missingKeys Array. Pass by reference. An array of the missing keys in $array as string values.
* #return Boolean. Return true only if all the values in $mustHaveKeys appear in $array as keys.
*/
function checkIfKeysExist($array, $mustHaveKeys, &$missingKeys = array()) {
// extract the keys of $array as an array
$keys = array_keys($array);
// ensure the keys we look for are unique
$mustHaveKeys = array_unique($mustHaveKeys);
// $missingKeys = $mustHaveKeys - $keys
// we expect $missingKeys to be empty if all goes well
$missingKeys = array_diff($mustHaveKeys, $keys);
return empty($missingKeys);
}
$arrayHasStoryAsKey = array('story' => 'some value', 'some other key' => 'some other value');
$arrayHasMessageAsKey = array('message' => 'some value', 'some other key' => 'some other value');
$arrayHasStoryMessageAsKey = array('story' => 'some value', 'message' => 'some value','some other key' => 'some other value');
$arrayHasNone = array('xxx' => 'some value', 'some other key' => 'some other value');
$keys = array('story', 'message');
if (checkIfKeysExist($arrayHasStoryAsKey, $keys)) { // return false
echo "arrayHasStoryAsKey has all the keys<br />";
} else {
echo "arrayHasStoryAsKey does NOT have all the keys<br />";
}
if (checkIfKeysExist($arrayHasMessageAsKey, $keys)) { // return false
echo "arrayHasMessageAsKey has all the keys<br />";
} else {
echo "arrayHasMessageAsKey does NOT have all the keys<br />";
}
if (checkIfKeysExist($arrayHasStoryMessageAsKey, $keys)) { // return false
echo "arrayHasStoryMessageAsKey has all the keys<br />";
} else {
echo "arrayHasStoryMessageAsKey does NOT have all the keys<br />";
}
if (checkIfKeysExist($arrayHasNone, $keys)) { // return false
echo "arrayHasNone has all the keys<br />";
} else {
echo "arrayHasNone does NOT have all the keys<br />";
}
I am assuming you need to check for multiple keys ALL EXIST in an array. If you are looking for a match of at least one key, let me know so I can provide another function.
Codepad here http://codepad.viper-7.com/AKVPCH
Hope this helps:
function array_keys_exist($searchForKeys = array(), $inArray = array()) {
$inArrayKeys = array_keys($inArray);
return count(array_intersect($searchForKeys, $inArrayKeys)) == count($searchForKeys);
}
This is old and will probably get buried, but this is my attempt.
I had an issue similar to #Ryan. In some cases, I needed to only check if at least 1 key was in an array, and in some cases, all needed to be present.
So I wrote this function:
/**
* A key check of an array of keys
* #param array $keys_to_check An array of keys to check
* #param array $array_to_check The array to check against
* #param bool $strict Checks that all $keys_to_check are in $array_to_check | Default: false
* #return bool
*/
function array_keys_exist(array $keys_to_check, array $array_to_check, $strict = false) {
// Results to pass back //
$results = false;
// If all keys are expected //
if ($strict) {
// Strict check //
// Keys to check count //
$ktc = count($keys_to_check);
// Array to check count //
$atc = count(array_intersect($keys_to_check, array_keys($array_to_check)));
// Compare all //
if ($ktc === $atc) {
$results = true;
}
} else {
// Loose check - to see if some keys exist //
// Loop through all keys to check //
foreach ($keys_to_check as $ktc) {
// Check if key exists in array to check //
if (array_key_exists($ktc, $array_to_check)) {
$results = true;
// We found at least one, break loop //
break;
}
}
}
return $results;
}
This was a lot easier than having to write multiple || and && blocks.
$colsRequired = ["apple", "orange", "banana", "grapes"];
$data = ["apple"=>"some text", "orange"=>"some text"];
$presentInBoth = array_intersect($colsRequired,array_keys($data));
if( count($presentInBoth) != count($colsRequired))
echo "Missing keys :" . join(",",array_diff($colsRequired,$presentInBoth));
else
echo "All Required cols are present";
Does this not work?
array_key_exists('story', $myarray) && array_key_exists('message', $myarray)
<?php
function check_keys_exists($keys_str = "", $arr = array()){
$return = false;
if($keys_str != "" and !empty($arr)){
$keys = explode(',', $keys_str);
if(!empty($keys)){
foreach($keys as $key){
$return = array_key_exists($key, $arr);
if($return == false){
break;
}
}
}
}
return $return;
}
//run demo
$key = 'a,b,c';
$array = array('a'=>'aaaa','b'=>'ccc','c'=>'eeeee');
var_dump( check_keys_exists($key, $array));
I am not sure, if it is bad idea but I use very simple foreach loop to check multiple array key.
// get post attachment source url
$image = wp_get_attachment_image_src(get_post_thumbnail_id($post_id), 'single-post-thumbnail');
// read exif data
$tech_info = exif_read_data($image[0]);
// set require keys
$keys = array('Make', 'Model');
// run loop to add post metas foreach key
foreach ($keys as $key => $value)
{
if (array_key_exists($value, $tech_info))
{
// add/update post meta
update_post_meta($post_id, MPC_PREFIX . $value, $tech_info[$value]);
}
}
$myArray = array('key1' => '', 'key2' => '');
$keys = array('key1', 'key2', 'key3');
$keyExists = count(array_intersect($keys, array_keys($myArray)));
Will return true, because there are keys from $keys array in $myArray
Something as this could be used
//Say given this array
$array_in_use2 = ['hay' => 'come', 'message' => 'no', 'story' => 'yes'];
//This gives either true or false if story and message is there
count(array_intersect(['story', 'message'], array_keys($array_in_use2))) === 2;
Note the check against 2, if the values you want to search is different you can change.
This solution may not be efficient, but it works!
Updates
In one fat function:
/**
* Like php array_key_exists, this instead search if (one or more) keys exists in the array
* #param array $needles - keys to look for in the array
* #param array $haystack - the <b>Associative</b> array to search
* #param bool $all - [Optional] if false then checks if some keys are found
* #return bool true if the needles are found else false. <br>
* Note: if hastack is multidimentional only the first layer is checked<br>,
* the needles should <b>not be<b> an associative array else it returns false<br>
* The array to search must be associative array too else false may be returned
*/
function array_keys_exists($needles, $haystack, $all = true)
{
$size = count($needles);
if($all) return count(array_intersect($needles, array_keys($haystack))) === $size;
return !empty(array_intersect($needles, array_keys($haystack)));
}
So for example with this:
$array_in_use2 = ['hay' => 'come', 'message' => 'no', 'story' => 'yes'];
//One of them exists --> true
$one_or_more_exists = array_keys_exists(['story', 'message'], $array_in_use2, false);
//all of them exists --> true
$all_exists = array_keys_exists(['story', 'message'], $array_in_use2);
Hope this helps :)
I usually use a function to validate my post and it is an answer for this question too so let me post it.
to call my function I will use the 2 array like this
validatePost(['username', 'password', 'any other field'], $_POST))
then my function will look like this
function validatePost($requiredFields, $post)
{
$validation = [];
foreach($requiredFields as $required => $key)
{
if(!array_key_exists($key, $post))
{
$validation['required'][] = $key;
}
}
return $validation;
}
this will output this
"required": [
"username",
"password",
"any other field"
]
so what this function does is validate and return all the missing fields of the post request.
// sample data
$requiredKeys = ['key1', 'key2', 'key3'];
$arrayToValidate = ['key1' => 1, 'key2' => 2, 'key3' => 3];
function keysExist(array $requiredKeys, array $arrayToValidate) {
if ($requiredKeys === array_keys($arrayToValidate)) {
return true;
}
return false;
}

how filter array recursive if match condition in php

lets say i have a array
array
array
key1 = 'hello im a text'
key2 = true;
key3 = '><><';
array
array
key1 = 'hello another text'
key2 = 'im a text too'
key3 = false;
array
key1 = ')(&#'
array
key1 = 'and so on'
how can i get something like below from the above arrays?
array
1 => 'hello im a text';
2 => 'hello another text;
3 => 'im a text too';
4 => 'and so on';
heres what ive done
$found = array();
function search_text($item, $key)
{
global $found;
if (strlen($item) > 5)
{
$found[] = $item;
}
}
array_walk_recursive($array, 'search_text');
var_dump($found);
but somehow it doesn't work
Try something similar to this:
function array_simplify($array, $newarray=array()) { //default of $newarray to be empty, so now it is not a required parameter
foreach ($array as $i) {
if (is_array($i)) { //if it is an array, we need to handle differently
$newarray = array_simplify($i, $newarray); // recursively calls the same function, since the function only appends to $newarray, doesn't reset it
continue; // goes to the next value in the loop, we know it isn't a string
}
if (is_string($i) && strlen($i)>5) { // so we want it in the one dimensional array
$newarray[] = $i; //append the value to $newarray
}
}
return $newarray; // passes the new array back - thus also updating $newarray after the recursive call
}
My note: I haven't tested this, if there's bugs, please tell me and I'll try to fix them.
Something like this should work,
as condition i've used
if(is_string($son))
in order to get some results, you can adjust it as you prefer
$input = <your input array>;
$output = array();
foreach($input AS $object)
{
search_text($object,$output);
}
var_dump($output);
function search_text($object, &$output)
{
foreach($object AS $son)
{
if(is_object($son))
{
search_text($son, $output);
}
else
{
if(is_string($son))
{
$output[] = $son;
}
}
}
}
Description:
search_text gets 2 parameters: the $object and the resulting array $output.
It checks foreach object's property if it is an object or not.
If it is then that object needs to be checked itself,
otherwise search_text checks if the input is a string, if it is the it is stored into the $output array

How to find a value in an array and remove it by using PHP array functions?

How to find if a value exists in an array and then remove it? After removing I need the sequential index order.
Are there any PHP built-in array functions for doing this?
<?php
$my_array = array('sheldon', 'leonard', 'howard', 'penny');
$to_remove = array('howard');
$result = array_diff($my_array, $to_remove);
?>
To search an element in an array, you can use array_search function and to remove an element from an array you can use unset function. Ex:
<?php
$hackers = array ('Alan Kay', 'Peter Norvig', 'Linus Trovalds', 'Larry Page');
print_r($hackers);
// Search
$pos = array_search('Linus Trovalds', $hackers);
// array_seearch returns false if an element is not found
// so we need to do a strict check here to make sure
if ($pos !== false) {
echo 'Linus Trovalds found at: ' . $pos;
// Remove from array
unset($hackers[$pos]);
}
print_r($hackers);
You can refer: https://www.php.net/manual/en/ref.array.php for more array related functions.
You need to find the key of the array first, this can be done using array_search()
Once done, use the unset()
<?php
$array = array( 'apple', 'orange', 'pear' );
unset( $array[array_search( 'orange', $array )] );
?>
Just in case you want to use any of mentioned codes, be aware that array_search returns FALSE when the "needle" is not found in "haystack" and therefore these samples would unset the first (zero-indexed) item. Use this instead:
<?php
$haystack = Array('one', 'two', 'three');
if (($key = array_search('four', $haystack)) !== FALSE) {
unset($haystack[$key]);
}
var_dump($haystack);
The above example will output:
Array
(
[0] => one
[1] => two
[2] => three
)
And that's good!
You can use array_filter to filter out elements of an array based on a callback function. The callback function takes each element of the array as an argument and you simply return false if that element should be removed. This also has the benefit of removing duplicate values since it scans the entire array.
You can use it like this:
$myArray = array('apple', 'orange', 'banana', 'plum', 'banana');
$output = array_filter($myArray, function($value) { return $value !== 'banana'; });
// content of $output after previous line:
// $output = array('apple', 'orange', 'plum');
And if you want to re-index the array, you can pass the result to array_values like this:
$output = array_values($output);
This solution is the combination of #Peter's solution for deleting multiple occurences and #chyno solution for removing first occurence. That's it what I'm using.
/**
* #param array $haystack
* #param mixed $value
* #param bool $only_first
* #return array
*/
function array_remove_values(array $haystack, $needle = null, $only_first = false)
{
if (!is_bool($only_first)) { throw new Exception("The parameter 'only_first' must have type boolean."); }
if (empty($haystack)) { return $haystack; }
if ($only_first) { // remove the first found value
if (($pos = array_search($needle, $haystack)) !== false) {
unset($haystack[$pos]);
}
} else { // remove all occurences of 'needle'
$haystack = array_diff($haystack, array($needle));
}
return $haystack;
}
Also have a look here: PHP array delete by value (not key)
The unset array_search has some pretty terrible side effects because it can accidentally strip the first element off your array regardless of the value:
// bad side effects
$a = [0,1,2,3,4,5];
unset($a[array_search(3, $a)]);
unset($a[array_search(6, $a)]);
$this->log_json($a);
// result: [1,2,4,5]
// what? where is 0?
// it was removed because false is interpreted as 0
// goodness
$b = [0,1,2,3,4,5];
$b = array_diff($b, [3,6]);
$this->log_json($b);
// result: [0,1,2,4,5]
If you know that the value is guaranteed to be in the array, go for it, but I think the array_diff is far safer. (I'm using php7)
$data_arr = array('hello', 'developer', 'laravel' );
// We Have to remove Value "hello" from the array
// Check if the value is exists in the array
if (array_search('hello', $data_arr ) !== false) {
$key = array_search('hello', $data_arr );
unset( $data_arr[$key] );
}
# output:
// It will Return unsorted Indexed array
print( $data_arr )
// To Sort Array index use this
$data_arr = array_values( $data_arr );
// Now the array key is sorted
First of all, as others mentioned, you will be using the "array_search()" & the "unset()" methodsas shown below:-
<?php
$arrayDummy = array( 'aaaa', 'bbbb', 'cccc', 'dddd', 'eeee', 'ffff', 'gggg' );
unset( $arrayDummy[array_search( 'dddd', $arrayDummy )] ); // Index 3 is getting unset here.
print_r( $arrayDummy ); // This will show the indexes as 0, 1, 2, 4, 5, 6.
?>
Now to re-index the same array, without sorting any of the array values, you will need to use the "array_values()" method as shown below:-
<?php
$arrayDummy = array_values( $arrayDummy );
print_r( $arrayDummy ); // Now, you will see the indexes as 0, 1, 2, 3, 4, 5.
?>
Hope it helps.
Okay, this is a bit longer, but does a couple of cool things.
I was trying to filter a list of emails but exclude certain domains and emails.
Script below will...
Remove any records with a certain domain
Remove any email with an exact value.
First you need an array with a list of emails and then you can add certain domains or individual email accounts to exclusion lists.
Then it will output a list of clean records at the end.
//list of domains to exclude
$excluded_domains = array(
"domain1.com",
);
//list of emails to exclude
$excluded_emails = array(
"bob#domain2.com",
"joe#domain3.com",
);
function get_domain($email) {
$domain = explode("#", $email);
$domain = $domain[1];
return $domain;
}
//loop through list of emails
foreach($emails as $email) {
//set false flag
$exclude = false;
//extract the domain from the email
$domain = get_domain($email);
//check if the domain is in the exclude domains list
if(in_array($domain, $excluded_domains)){
$exclude = true;
}
//check if the domain is in the exclude emails list
if(in_array($email, $excluded_emails)){
$exclude = true;
}
//if its not excluded add it to the final array
if($exclude == false) {
$clean_email_list[] = $email;
}
$count = $count + 1;
}
print_r($clean_email_list);
To find and remove multiple instance of value in an array, i have used the below code
$list = array(1,3,4,1,3,1,5,8);
$new_arr=array();
foreach($list as $value){
if($value=='1')
{
continue;
}
else
{
$new_arr[]=$value;
}
}
print_r($new_arr);

Categories