PHP - Check if an array value is in another array - php

So I have two arrays:
$gated_categories
array(2) { [0]=> int(3511) [1]=> int(3510) }
and
$category_id
array(3) { [0]=> int(3518) [1]=> int(3511) [2]=> int(3502) }
As you can see above, both arrays contain 3511
So if $gated_categories contains a value which is is $category_id
I want this to return true, else false
I have tried with this:
$is_gated = !array_diff($gated_categories, $category_id);
But this is returning false, any ideas?

array_diff() does the opposite of what you want. It returns an array with the values of the first array that are not present in the other array(s).
You need array_intersect().
if (count(array_intersect($arr1, $arr2))) {
//at least one common value in both arrays
}

You can do the following, loop over the array you want to check it's values and use in_array function.
Something like this:
<?php
function checkCategory(): bool {
$gated_categories = [3510, 3511];
$category_id = [3502, 3511, 3518];
foreach ($gated_categories as $cat) {
if (in_array($cat, $category_id)) {
return true;
}
}
return false;
}
var_dump(checkCategory());

You can solve this problem with use from array_diff two times
<?php
$gated_categories = [3511, 3510];
$category_id = [3518, 3511, 3502];
print_r(findGatedCategoriesContainCategoryId($gated_categories, $category_id));
function findGatedCategoriesContainCategoryId($gated_categories, $category_id) {
$arrayDiff = array_diff($gated_categories, $category_id);
return array_values(array_diff($gated_categories ,$arrayDiff));
}
?>
output
Array
(
[0] => 3511
)
Or just use array_intersect like this
<?php
$gated_categories = [3511, 3510];
$category_id = [3518, 3511, 3502];
$result = array_intersect($gated_categories, $category_id);
print_r($result);
?>
output
Array
(
[0] => 3511
)

Related

get array from an array of array using value

I have an array of array like this
$data=array(
array("9900","1","7"),
array("9901","1","7"),
array("9902","1","7"),
array("9903","1","4"),
array("9904","3","8"),
array("9908","1","5")
);
I have value 9908. When I search 9908 then the value array("9908","1","5") should be printed. I have used array_search() but I have not got any success
How I can print the array after finding the value
Try this:
var_dump($data[array_search("9908", array_column($data, 0))]);
To expand it,
array_column returns the values from a single column of the input, identified by the column_key. Optionally, an index_key may be provided to index the values in the returned array by the values from the index_key column of the input array.
array_search Searches the array for a given value and returns the first corresponding key if successful.
Edit:
To add some control over it:
$index = array_search("9908", array_column($data, 0));
if($index !== false){
// do your stuff with $data[$index];
var_dump($data[$index]);
}
Dumps:
array(3) {
[0]=>
string(4) "9908"
[1]=>
string(1) "1"
[2]=>
string(1) "5"
}
Perhaps this can help:
<?php
function search_first_row($needle, $haystack){
$data = $haystack;
$desired_value = $needle;
foreach($data as $row){
if($row[0] == $desired_value){
return $row;
}
}
}
try this :
$data=array(
array("9900","1","7"),
array("9901","1","7"),
array("9902","1","7"),
array("9903","1","4"),
array("9904","3","8"),
array("9908","1","5")
);
foreach ($data as $key => $value) {
if( in_array("9908",$value)){
$findindex = $key;
}
}
var_dump($data[$findindex]);
$data=array(
array("9900","1","7"),
array("9901","1","7"),
array("9902","1","7"),
array("9903","1","4"),
array("9904","3","8"),
array("9908","1","5")
);
$searchValue = '9908';
for($i=0; $i<count($data); $i++){
$innerArray = $data[$i];
for($j=0; $j<count($innerArray); $j++){
if($innerArray[$j] == $searchValue){
print_r($innerArray);
}
}
}

Change value within array based on input in php

I am trying to locale the correct sub-array in order to change the count, if a specific value is present more than once.
I have the following code:
$trending = [];
foreach($hashtags as $hashtag) {
if(in_array($hashtag->hashtag, $hashtags))
{
array_search()
}
else {
array_push($trending, [
'hashtag' => $hashtag->hashtag,
'counts' => '1'
]);
}
}
This gives me the following example outout:
array(3) {
[0]=> array(2)
{
["hashtag"]=> "foobar"
["counts"]=> "1"
}
[1]=> array(2)
{
["hashtag"]=> "hashtags"
["counts"]=> "1"
}
[2]=> array(2)
{
["hashtag"]=> "imageattached"
["counts"]=> "1"
}
}
So in the foreach loop and the if statement, i want to check for dublicates of hashtags, e.g. if the hashtag foobar exists more than one time, I don't want to create another dublicate in the array, but I want to change the count to 2
How do I find the correct "sub"-array, and change the count of this to 2, if a hashtag is present within $hashtags more than once??
The idea is, that I at the end can sort these arrays, and get the hashtag that is most common, by looking at the count.
If you change the structure of your output, you could do something like this:
$trending = [];
foreach($hashtags as $tag) {
if (isset($trending[$tag])) $trending[$tag]++;
else $trending[$tag] = 1;
}
Which would result in $trending having the structure
array(2) {
["foobar"] => 1,
["hashtags"] => 2
}
Which could then be looped through with
foreach($trending as $tag => $count) {
echo $tag . ' appears ' . $count . ' times.' . PHP_EOL;
}
The PHP method array_count_values might be of some help.
http://php.net/manual/en/function.array-count-values.php
Have you considered using a keyed array?
$trending = array();
foreach($hashtags as $hashtag) {
if(!isset($trending[$hashtag])){
$trending[$hashtag] = 1;
}else{
$trending[$hashtag] += 1;
}
}
By using a keyed array, there is no duplication and you can easily check how frequently a hashtag is used by just accessing $trending[$hashtag]. Additionally, you can get the list of all hashtags in the trending array using $allHashtags = array_keys($trending);.
Of course, if your project specifications do not allow for this, then by all means, use a different approach, but that would be the approach I would take.
It can be more linear of you can change your array structure but for the current this should work.
$trending = [];
$checker = true;
foreach($hashtags as $hashtag) {
foreach ($trending as $key =>$value) {
if($value["hashtag"] == $hashtag->hashtag){
$trending[$key]["counts"]++;
$checker = false;
}
}
if($checker) {
array_push($trending, [
'hashtag' => $hashtag->hashtag,
'counts' => '1'
]);
}
$checker = true;
}

How to create an array based on value in PHP?

I have an array like this
Array
(
[0] => 123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-31).pdf
[1] => 123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-30).pdf
[2] => 123_bms_for__on__(10-06-2015_18-36).pdf
)
I want to convert this into multidimensional array based on its value such
as
Array
(
[dr] => Array
(
[0] => 123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-31).pdf
[1] => 123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-30).pdf
)
[bms] => Array
(
[0] => 123_bms_for__on__(10-06-2015_18-36).pdf
)
)
based on name after first underscore (bms,dr) like....... Please help me to achieve this
I would do the following:
$newArray = array();
foreach ($array as $key => $value) {
$parts = explode('_', $value);
$newArray[$parts[1]][] = $value;
}
print_r($newArray);
To solve this without a loop, it would be smart to use a function along with built in Array Filter function.
Here's another possible solution - which seems a little cooler I suppose;
<?php
// ####################
// GLOBAL VARIABLES DEFINITION
// ####################
// Store Pattern Here = Used to Define Array at the end
global $Array_IDs;
$Array_IDs = array();
// Store Variables With Header Pattern (ID) in this area
global $Array_Values;
$Array_Values = array();
// ####################
// FUNCTION DEFINITION
// ####################
// FUNCTION TO SPLIT ARRAY
function Get_ID($variable){
// ACCESS GLOBALS
global $Array_IDs;
global $Array_Values;
// GET CURRENT VARIBALE - EXPLODE TO EXTRACT PATTERN AS ID
$Temp_Parts = explode("_", $variable);
// CHECK IF IDENTIFIER IS ALREADY FOUND (STORED IN ARRAY_ID)
if (in_array($Temp_Parts[1], $Array_IDs)){
// ID ALREADY HAS SUB-ARRAY CREATED
// JUST APPEND VARIABLE
$Array_Values[$Temp_Parts[1]][] = $variable;
}else{
// ADD ID TO Array_IDs
$Array_IDs[] = $Temp_Parts[1];
// Create New ARRAY with HEADER AS PATTERN - ID
$Array_Values[$Temp_Parts[1]][] = $variable;
}
}
// ####################
// CODE STARTS HERE == ONLY THREE LINES ;)
// ####################
$Start_Array = array('123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-31).pdf','123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-30).pdf','123_bms_for__on__(10-06-2015_18-36).pdf');
array_filter($Start_Array,"Get_ID");
print_r($Array_Values);
?>
Give it a try and let me know how it goes, the output is as requested ;)
You can use array_reduce function and regex matching for elegant & lesser code.
$array = array(
'0'=>'123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-31).pdf',
'1'=>'123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-30).pdf',
'2'=>'123_bms_for__on__(10-06-2015_18-36).pdf'
);
$result = array_reduce($array, function($prod, $current){
preg_match('/(?<=^123_)\w+(?=_for\w+)/',$current,$match);
$prod[$match[0]][] = $current;
return $prod;
}, []);
Will produce the following result.
array(2) {
[0]=>
string(57) "123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-31).pdf"
[1]=>
string(57) "123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-30).pdf"
}
array(1) {
[0]=>
string(39) "123_bms_for__on__(10-06-2015_18-36).pdf"
}
Using square bracket require PHP 5.4 above, you can replace with array() instead for lower version of PHP.
please find below code as per your requirement.
<?php
$array = array(
'0'=>'123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-31).pdf',
'1'=>'123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-30).pdf',
'2'=>'123_bms_for__on__(10-06-2015_18-36).pdf'
);
$dr_array = array();
$bms_array = array();
foreach($array as $val){
$str_explode = explode("_",$val);
if($str_explode[1]=="dr"){
$dr_array[] = $val;
}
else if($str_explode[1]=="bms"){
$bms_array[] = $val;
}
}
var_dump($dr_array);
var_dump($bms_array);
?>
Output :
array(2) {
[0]=>
string(57) "123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-31).pdf"
[1]=>
string(57) "123_dr_for_ma_on_2352015_2nd Shift_(08-29-2015_11-30).pdf"
}
array(1) {
[0]=>
string(39) "123_bms_for__on__(10-06-2015_18-36).pdf"
}
Thanks.
$basicArray = array(); //It Stores All The Elements
$firstArray = array(); //It will store array elements of first type
$secondArray = array(); //It will store array elements of second type
for($i = 0; $i < count($basicArray); $i++)
{
$elementArray = explode("_", $basicArray[i]);
if($elementArray[1] == "dr")
array_push($firstArray, $basicArray[i]);
else if($elementArray[1] == "bms")
array_push($secondArray, $basicArray[i]);
}
$finalArray = array();
array_push($finalArray, $firstArray, $secondArray);

array_search() in Session Array

I tried to use the function array_search but can't get it work..
I got a php session with an array.
array(2) {
[0]=>
array(6) {
["ProductId"]=>string(2) "34"
["ProductName"]=>string(9) "Best ever"
["ProductPrice"]=>string(6) "453.00"
["ProductColor"]=>string(4) "Blue"
["ProductSize"]=>string(1) "S"
["Image"]=>string(36) "d12f95895c9130da8e52a7ff5b9216c9.png"
}
[1]=>
array(6) {
["ProductId"]=>string(2) "33"
["ProductName"]=>string(5) "Vespa"
["ProductPrice"]=>string(7) "1789.00"
["ProductColor"]=>string(4) "Blue"
["ProductSize"]=>string(1) "S"
["Image"]=>string(36) "678e25ea94a7fa94bc6fa427ff29bc6c.png"
}
now I do an array_search()
session_start();
include '_sqlclean.php';
(isset($_POST['product_id'])) ? $p_id = clean_string_save($_POST['product_id']) : $p_id = 0;
$array = $_SESSION['wishList'];
$key = array_search($p_id, $array);
if I do a
var_dump($_SESSION['wishList']);
I got what I showed you above.
But I always got the message "Key not found"
Why ?? What's my mistake ?
I tried already to do
$p_id = "34" // for try
$p_id = intval(34); // for try also
$key = array_search("34", $_SESSION['wishList']); // to see if it works
but nothing worked.. :(
Thanks in advance
array_search will not work for multidimensional arrays. Rather this might work -
$key = array_search($p_id, array_column($array, 'ProductId'));
This will extract all the ProductId from that array then do the search.
Try with alternative for array_search().For example:
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['uid'] === $id) {
return $key;
}
}
return null;
}
OR
$key = array_search($p_id, array_column($array, 'ProductId'));
Aparently you are mistyping the variable (key) name
in the array it is
ProductId
and in your code it is
Product_Id
It happen cause you search into outer array, which contains only [0] and [1] keys.
Try to use
$key = array_search("34", $_SESSION['wishList'][1]);
You can try an alternative way like
<?php
$p_id = "34" // for try
$p_id = intval(34); // for try also
if(in_array($p_id, array_values($_SESSION['wishList']))) {
// Product Id found in your wishList
}
?>
It will works only for single dimension array. For multidimensional use foreach loop.

How to create a nested array out of an array in PHP

Say, we have an array: array(1,2,3,4,...)
And I want to convert it to:
array(
1=>array(
2=>array(
3=>array(
4=>array()
)
)
)
)
Can anybody help?
Thanks
EDIT It would be good to have the solution with iterations.
$x = count($array) - 1;
$temp = array();
for($i = $x; $i >= 0; $i--)
{
$temp = array($array[$i] => $temp);
}
You can simply make a recursive function :
<?php
function nestArray($myArray)
{
if (empty($myArray))
{
return array();
}
$firstValue = array_shift($myArray);
return array($firstValue => nestArray($myArray));
}
?>
Well, try something like this:
$in = array(1,2,3,4); // Array with incoming params
$res = array(); // Array where we will write result
$t = &$res; // Link to first level
foreach ($in as $k) { // Walk through source array
if (empty($t[$k])) { // Check if current level has required key
$t[$k] = array(); // If does not, create empty array there
$t = &$t[$k]; // And link to it now. So each time it is link to deepest level.
}
}
unset($t); // Drop link to last (most deep) level
var_dump($res);
die();
Output:
array(1) {
[1]=> array(1) {
[2]=> array(1) {
[3]=> array(1) {
[4]=> array(0) {
}
}
}
}
}
I think the syntax for the multidimensional array you want to create would look like the following.
$array = array(
'array1' => array('value' => 'another_value'),
'array2' => array('something', 'something else'),
'array3' => array('value', 'value')
);
Is this what you're looking for?
You can also use this array library to do that in just one line:
$array = Arr::setNestedElement([], '1.2.3.4', 'value');

Categories