Search in 2 arrays - php

I have problem with search in arrays , in 2 arrays , the first array have one structure fixed and the second send the vars from url and can have some values empty , for example
FIRST ARRAY :
The structure it's this :
id value , cat value , subcat value and country value
$ar_val="134567,dogs,food,EEUU";
The second var get from URL
$ar_url="134567,dogs,toys,EEUU";
As you can see in the second var , $ar_url i have one value no same to the first structure of $ar_val in this case toys
I want get compare the fixed structure of $ar_val and get if true or false if have same value in the same order from $ar_val
I try this :
$ar_val="134567,dogs,food,EEUU";
$ar_url="134567,dogs,toys,EEUU";
$exp_ar_val=explode(",",$ar_val);
$exp_ar_url=explode(",",$ar_url);
foreach ($exp_ar_val as $exp_ar_val2)
{
$ar_val_end[]=$exp_ar_val2;
}
foreach ($exp_ar_url as $exp_ar_url2)
{
$ar_val_end2[]=$exp_ar_url2;
}
$end_results=array_intersect($ar_val_end,$ar_val_end2);
With this I want know for example: If I search by id and for example for cat , get result positive in 2 arrays i have the same data , but if search for subcat i can´t get results because are differents in one have food and in other have toys , but with array_intersect no get this for compare
Thank´s , Regards

I think he wants to check if a value exists in either array. try this...
<?
function inarray($value,$array=array()){
if(in_array($value,$array)){
return true;
}else{
return false;
}
}
$ar_val=array("134567","dogs","food","EEUU");
$ar_url=array("134567","dogs","toys","EEUU");
$a = inarray("food",$ar_val);
$b = inarray("food",$ar_url);
if($a!=false and $b!=false)
echo "Found in both arrays";
elseif($a==true and $b==false)
echo "Found in first array";
elseif($a==false and $b==true)
echo "Found in second array";
else
echo "Not Found in any array";
?>

Try this:
$ar_val="134567,dogs,food,EEUU";
$ar_url="134567,dogs,toys,EEUU";
$arrayVal = explode(',', $ar_val);
$arrayUrl = explode(',', $ar_url);
$maxLength = max(sizeof($arrayVal), sizeof($arrayUrl));
$arrayIdsEqual = array();
$arrayIdsDifferent = array();
for ($i = 0; $i < $maxLength; $i++) {
if (isset($arrayVal[$i]) && isset($arrayUrl[$i])) {
if ($arrayVal[$i] == $arrayUrl[$i]) {
$arrayIdsEqual[] = $i;
}
else {
$arrayIdsDifferent[] = $i;
}
}
else {
//you arrive here if you have 2 arrays that don't have the same size / sme number of variables
}
}
//assuming your 2 arrays ALWAYS have the same size, you can use the following logic
if (empty($arrayIdsDifferent)) {
echo '2 arrays are the same';
}
else {
echo "Differences: \n";
foreach ($arrayIdsDifferent as $indexDifferent => $currentIdDifferent) {
$output = 'difference ' . ($indexDifferent + 1) . ': ';
$output .= 'val = ' . $arrayVal[$currentIdDifferent];
$output .= '; ';
$output .= 'url = ' . $arrayUrl[$currentIdDifferent];
echo $output;
echo "\n";
}
}
You can see this working here: http://3v4l.org/pTQns

You can use array_diff for this, which is perfect for comparison purposes:
<?php
$ar_val= array ("0" => "134567", "1" => "dogs", "2" => "food", "3" => "EEUU");
$ar_url= array ("0" => "134567", "1" => "dogs", "2" => "EEUU", "3" => "food");
$result = array_diff($ar_val, $ar_url);
$num = 0;
if ($result != NULL) {
echo "unique array keys: TRUE" . "\n\n";
print_r($result);
echo "\n\n";
} else {
echo "unique array keys: FALSE" . "\n\n";
}
foreach($ar_val as $key) {
if ($ar_val[$num] != $ar_url[$num]) {
echo "intersecting array key different: TRUE" . "\n> ";
print_r($ar_val[$num]);
echo "\n\n";
}
$num++;
}
?>

Just compare them with equal without any complicated operations.
$ar_val = "134567,dogs,food,EEUU";
$ar_url = "134567,dogs,toys,EEUU";
$exp_ar_val = explode(",", $ar_val);
$exp_ar_url = explode(",", $ar_url);
var_dump($exp_ar_val == $exp_ar_url); // false, elements does not match
$exp_ar_url = $exp_ar_val;
var_dump($exp_ar_val == $exp_ar_url); // true, all elements match
shuffle($exp_ar_url);
var_dump($exp_ar_val == $exp_ar_url); // false, different order

Related

How can I echo the right key in my multidimensional associative array?

My objective is to create a multidimensional associative array with friends and their dreams (user input) in it. I think (hope) that I can am close to finishing it, but I get an unwanted result when echoing the final step:
I am trying to echo a sentence including the name of a 'friend' on line 22. Instead of a name inputted by the user, I get 'Array' as a result. E.g.: Array has this as their dream: Climbing Mount Everest
Does anyone know how I get the name of the friend here?
A line/string should be echoed for every separate dream that was filled in. And I included the print function for my clarity, will delete later. Thanks!
<?php
$friends = readline('How many friends should we ask for their dreams? ');
$array = [];
if (is_numeric($friends) == false) {
exit("This is not a number." . PHP_EOL);
} else if ($friends == 0) {
exit("This is not valid input." . PHP_EOL);
} else {
for ($i = 1; $i <= $friends; $i++) {
$name_key = readline('What is your name? ');
$number_dreams = readline('How many dreams are you going to enter? ');
for ($x = 1; $x <= $number_dreams; $x++) {
$dream_value = readline('What is your dream? ');
$array[$name_key][] = $dream_value;
}
print_r($array);
}
foreach ($array as $friend) {
foreach ($friend as $key => $value) {
echo $friend . ' has this as their dream: ' . $value . PHP_EOL;
}
}
}
try this after you assembled $array:
foreach ($array as $frndNm=>$dreams){
foreach($dreams as $dream){
echo( $frndNm.' dream is '.$dream);
}
}

Check for empty values in associative array

I'm having a hard time checking for empty values in my associative array. And if a value is empty/null replace it with the wording "not entered"
My $_SESSION['gift'] array:
Array
(
[0] => Array
(
[giftGiveMy] => 1a
[giftTo] => 2a
)
[1] => Array
(
[giftGiveMy] => 1b
[giftTo] => '' //### empty ###
)
)
if (empty($_SESSION['gift']) && 0 !== $_SESSION['gift']) {
$gifts = "No specific gifts identified.\n";
} else {
$gifts = [];
foreach( $_SESSION['gift'] as $value) {
$gifts[] = "I give my ". $value['giftGiveMy'] ." to ". $value['giftTo'] .".\n";
}
$gifts = join($gifts);
}
The above outputs:
I give my 1a to 2a.
I give my 1b to .
I would like it read:
I give my 1a to 2a.
I give my 1b to not entered.
You can replace all empty and NULL value with not entered with the help of array_walk_recursive and use you code as it is
array_walk_recursive($arrayMain, 'not_entered');
function not_entered(& $item, $key) {
if (($item === "") || ($item ==NULL)){
$item = "not entered";
}
}
var_dump($arrayMain);
Just use foreach to loop all values and check if it's empty
$emptyText = '<b>not entered</b>';
// `empty` will also be true if element does not exist
if (empty($_SESSION['gift'])) {
$gifts = "No specific gifts identified.\n";
} else {
$gifts = [];
foreach($_SESSION['gift'] as $value) {
$myGive = !empty($value['giftGiveMy']) ? $value['giftGiveMy'] : $emptyText;
$giftTo = !empty($value['giftTo']) ? $value['giftTo'] : $emptyText;
$gifts[] = "I give my {$myGive} to {$giftTo}.";
}
$gifts = implode("\r\n", $gifts); // Or `<br/>` if outputted to HTML
}
You should modify your code and write it this way:
if (!isset($_SESSION['gift']) || empty($_SESSION['gift'])) {
$gifts = "No specific gifts identified.\n";
} else {
foreach( $_SESSION['gift'] as $value) {
$gift_to = !empty($value['giftTo']) ? $value['giftTo'] : '<strong>Not entered<strong>';
$gifts[] = "I give my ". $value['giftGiveMy'] ." to ". $gift_to .".\n";
}
}
You might want to try this:
if (empty($_SESSION['gift']) && 0 !== $_SESSION['gift']) {
$gifts = "No specific gifts identified.\n";
} else {
$gifts = [];
foreach( $_SESSION['gift'] as $value) {
$gifts[] = "I give my ". $value['giftGiveMy'] ." to ". (!empty($value['giftTo']) ? $value['giftTo'] : '<b>not entered</b>') .".\n";
}
$gifts = join($gifts);
}
If you would like to make it a little cleaner you could extract the ternary operator into something like this;
$giftTo = !empty($value['giftTo']) ? $value['giftTo'] : '<b>not entered</b>';
$gifts[] = "I give my ". $value['giftGiveMy'] ." to ". $giftTo .".\n";
Try:
$arr = $_SESSION['gift'];
foreach($arr as $key => $array) {
if($array['giftGiveMy'] == null || empty($array['giftGiveMy'])) {
$arr[$key]['giftGiveMy'] = 'not entered.';
}
if($array['giftTo'] == null || empty($array['giftTo'])) {
$arr[$key]['giftTo'] = 'not entered.';
}
}
I'd write that this way:
$gifts = "No specific gifts identified.\n";
$filter = function($str) {
return empty($str) ? 'not entered' : $str;
};
if(!empty($_SESSION['gift'])) {
$gifts = '';
array_walk($_SESSION['gift'], function($given) use(&$gifts,$filter){
$gifts .= 'I give my ' . $filter($given['giftGiveMy']) . ' to ' . $filter($given['giftTo']) . ".\n";
});
}
You can use for the below code also there is no need any extra Php functions.
$arr = array(
0 => array(
'giftGiveMy' => '1a',
'giftTo' => '2a'
),
1 => array(
'giftGiveMy' => '1b',
'giftTo' => ''
)
);
$str = '';
if (!empty($arr)) {
foreach ($arr as $key => $value) {
if ($value['giftGiveMy'] == '')
$value['giftGiveMy'] = 'not entered';
if ($value['giftTo'] == '')
$value['giftTo'] = '<strong>not entered</strong>';
//$new[$key] = $value;
$str .= "I give my " . $value['giftGiveMy'] . " to " . $value['giftTo'] . "<br />";
}
}else {
$str = 'No specific gifts identified.<br />';
}
echo $str;
This validates an associative array with empty() (see array_filter), but may not respond to the original question.
<?php
$var = array();
$var['position'] = 'executive';
$var['email'] = 'a#email.com';
$var['message'] = 'This is the message';
$var['name'] = 'John Doe';
$var['telephone'] = '123456789';
$var['notneededparam'] = 'Nothing';
$expectedParams = ['position', 'email', 'message', 'name', 'telephone'];
$params = array_intersect_key($var, array_flip($expectedParams));
// check existence of keys and that they are valid
if(count($params) != count($expectedParams) || count(array_filter($params)) != count($expectedParams)){
echo "not valid\n";
die();
}
extract($params);
var_dump($name);
Other functions used here: array_flip(), array_intersect_key(), count(), extract(), var_dump(),

Issue with array need to adjust string

Hello there guys so first of all, I have this code:
$crumbs = array();
$crumbs[] = "Triple O Dental Laboratory";
if (is_array($GLOBALS["cookie_crumbs"])) {
foreach($GLOBALS["cookie_crumbs"] as $mycrumb) {
$mycrumb[1] = str_replace("//","/",$mycrumb[1]);
$crumbs[] = "".$mycrumb[0]." > Smile TRU";
}
}
print "<div class=\"cookie_crumbs2\">\n";
print implode(" > ",$crumbs);
print "</div>\n";
Now the problem is, i am trying to remove this part of the code:
> Smile TRU";
But only from the LAST item in the array, so pretty much at the moment its getting output like this: http://puu.sh/74ure.png
But I want the " > big one" taken away from the last item which is "Accreditation Video".
Try this :
$crumbs = array();
$crumbs[] = "Triple O Dental Laboratory";
if (is_array($GLOBALS["cookie_crumbs"])) {
foreach($GLOBALS["cookie_crumbs"] as $mycrumb) {
if(end($GLOBALS["cookie_crumbs"] != $mycrumb)){
$mycrumb[1] = str_replace("//","/",$mycrumb[1]);
$crumbs[] = "".$mycrumb[0]." > Smile TRU";
}
else{
$mycrumb[1] = str_replace("//","/",$mycrumb[1]);
$crumbs[] = "".$mycrumb[0]."";
}
}
}
print "<div class=\"cookie_crumbs2\">\n";
print implode(" > ",$crumbs);
print "</div>\n";
First count the crumbs and then, in the loop, check if You are handling the last one or not. Provided that the "cookie_crumbs" is array indexed numerically form 0:
$last = count($GLOBALS["cookie_crumbs"]) - 1;
foreach ($GLOBALS["cookie_crumbs"] as $index => $mycrumb) {
if ($index === $last) {
$crumbs[] = 'I am the last one'; // do whatever You need here...
}
else {
$mycrumb[1] = str_replace("//","/",$mycrumb[1]);
$crumbs[] = "".$mycrumb[0]." > Smile TRU";
}
}

Help with PHP loop

Suppose I have a multi-dimensional array of the form:
array
(
array('Set_ID' => 1, 'Item_ID' => 17, 'Item_Name' = 'Whatever'),
array('Set_ID' => 1, 'Item_ID' => 18, 'Item_Name' = 'Blah'),
array('Set_ID' => 2, 'Item_ID' => 19, 'Item_Name' = 'Yo')
)
The array has more sub-arrays, but that's the basic form-- Items in Sets.
How can I loop through this array so that I can echo the number of items in each set along with the all the items like so:
Set 1 has 2 Items: 17: Whatever and 18: Blah
Set 2 has 1 Items: 19: Yo
I'm aware that this could be done with two loops-- one to build an array, and another to loop through that array. However, I'd like to do this all with only one loop.
In your answer, you should assume that there are two display functions
display_set($id, $count) //echo's "Set $id has $count Items"
display_item($id, $name) //echo's "$id: $name"
UPDATE: Forgot to mention that the data is sorted by Set_ID because its from SQL
Right, all the examples below rely on an ordered set, the OP states it is ordered initially, but if needed a sort function could be:
// Sort set in to order
usort($displaySet,
create_function('$a,$b',
'return ($a['Set_ID'] == $b['Set_ID']
? ($a['Set_ID'] == $b['Item_ID']
? 0
: ($a['Item_ID'] < $b['Item_ID']
? -1
: 1))
: ($a['Set_ID'] < $b['Set_ID'] ? -1 : 1));'));
Straight example using a single loop:
// Initialise for the first set
$cSetID = $displaySet[0]['Set_ID'];
$cSetEntries = array();
foreach ($displaySet as $cItem) {
if ($cSetID !== $cItem['Set_ID']) {
// A new set has been seen, display old set
display_set($cSetID, count($cSetEntries));
echo ": " . implode(" and ", $cSetEntries) . "\n";
$cSetID = $cItem['Set_ID'];
$cSetEntries = array();
}
// Store item display for later
ob_start();
display_item($cItem['Item_ID'], $cItem['Item_Name');
$cSetEntries[] = ob_get_clean();
}
// Perform last set display
display_set($cSetID, count($cSetEntries));
echo ": " . implode(" and ", $cSetEntries) . "\n";
Using a recursive function it could be something like this:
// Define recursive display function
function displayItemList($itemList) {
if (!empty($itemList)) {
$cItem = array_shift($itemList);
display_item($cItem['Item_ID'], $cItem['Item_Name');
if (!empty($itemList)) {
echo " and ";
}
}
displayItemList($itemList);
}
// Initialise for the first set
$cSetID = $displaySet[0]['Set_ID'];
$cSetEntries = array();
foreach ($displaySet as $cItem) {
if ($cSetID !== $cItem['Set_ID']) {
// A new set has been seen, display old set
display_set($cSetID, count($cSetEntries));
echo ": ";
displayItemList($cSetEntries);
echo "\n";
$cSetID = $cItem['Set_ID'];
$cSetEntries = array();
}
// Store item for later
$cSetEntries[] = $cItem;
}
// Perform last set display
display_set($cSetID, count($cSetEntries));
echo ": ";
displayItemList($cSetEntries);
echo "\n";
Amusingly, it can be one single recursive function:
function displaySetList($setList, $itemList = NULL) {
// First call, start process
if ($itemList === NULL) {
$itemList = array(array_shift($setList));
displaySetList($setList, $itemList);
return;
}
// Check for display item list mode
if ($setList === false) {
// Output first entry in the list
$cItem = array_shift($itemList);
display_item($cItem['Item_ID'], $cItem['Item_Name']);
if (!empty($itemList)) {
// Output the next
echo " and ";
displaySetList(false, $itemList);
} else {
echo "\n";
}
return;
}
if (empty($setList) || $setList[0]['Set_ID'] != $itemList[0]['Set_ID']) {
// New Set detected, output set
display_set($itemList[0]['Set_ID'], count($itemList));
echo ": ";
displaySetList(false, $itemList);
$itemList = array();
}
// Add next item and carry on
$itemList[] = array_shift($setList);
displaySetList($setList, $itemList);
}
// Execute the function
displaySetList($displaySet);
Note that the recursive example here is grossly inefficient, a double loop is by far the quickest.
<?php
$sets = array();
foreach ($items as $item)
{
if (!array_key_exists($item['Set_ID'], $sets))
{
$sets[$item['Set_ID']] = array();
}
$sets[$item['Set_ID']][] = $item;
}
foreach ($sets as $setID => $items)
{
echo 'Set ' . $setID . ' has ' . count($items) . ' Items: ';
foreach ($items as $item)
{
echo $item['Item_ID'] . ' ' . $item['Item_Name'];
}
}
?>
Something like this i guess?
EDIT:
After i posted this i saw the display functions where added. But you get the point.
The need to not print out any items until we know how many there are in the set makes this difficult. At some point, we'll need to doing some buffering, or else backtracking. However, if I'm allowed internal loops, and sets are contiguous in the "master" array, then with some hacking around:
$set = 0;
$items;
foreach ($arr as $a) {
if ($a['Set_ID'] != $set) {
if ($set != 0) {
display_set($set, count($items));
foreach ($items as $i)
display_item($i)
}
$set = $a['Set_ID'];
$items = array();
}
$items[] = $a;
}
How about this:
$previous_set = false;
$items = '';
$item_count = 0;
foreach ($rows as $row)
{
if ($row['Set_ID'] != $previous_set)
{
if ($previous_set)
{
echo display_set($row['Set_ID'], $item_count);
echo $items;
}
$previous_class = $row['Set_ID'];
$item_count = 0;
$items = '';
}
$items .= display_item($row['Item_ID'], $row['Title']);
$item_count++;
}
echo display_set($row['Set_ID'], $item_count);
echo $items;

How can I easily remove the last comma from an array?

Let's say I have this:
$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");
foreach($array as $i=>$k)
{
echo $i.'-'.$k.',';
}
echoes "john-doe,foe-bar,oh-yeah,"
How do I get rid of the last comma?
Alternatively you can use the rtrim function as:
$result = '';
foreach($array as $i=>$k) {
$result .= $i.'-'.$k.',';
}
$result = rtrim($result,',');
echo $result;
I dislike all previous recipes.
Php is not C and has higher-level ways to deal with this particular problem.
I will begin from the point where you have an array like this:
$array = array('john-doe', 'foe-bar', 'oh-yeah');
You can build such an array from the initial one using a loop or array_map() function. Note that I'm using single-quoted strings. This is a micro-optimization if you don't have variable names that need to be substituted.
Now you need to generate a CSV string from this array, it can be done like this:
echo implode(',', $array);
One method is by using substr
$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");
$output = "";
foreach($array as $i=>$k)
{
$output .= $i.'-'.$k.',';
}
$output = substr($output, 0, -1);
echo $output;
Another method would be using implode
$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");
$output = array();
foreach($array as $i=>$k)
{
$output[] = $i.'-'.$k;
}
echo implode(',', $output);
I don't like this idea of using substr at all, since it's the style of bad programming. The idea is to concatenate all elements and to separate them by special "separating" phrases. The idea to call the substring for that is like to use a laser to shoot the birds.
In the project I am currently dealing with, we try to get rid of bad habits in coding. And this sample is considered one of them. We force programmers to write this code like this:
$first = true;
$result = "";
foreach ($array as $i => $k) {
if (!$first) $result .= ",";
$first = false;
$result .= $i.'-'.$k;
}
echo $result;
The purpose of this code is much clearer, than the one that uses substr. Or you can simply use implode function (our project is in Java, so we had to design our own function for concatenating strings that way). You should use substr function only when you have a real need for that. Here this should be avoided, since it's a sign of bad programming style.
I always use this method:
$result = '';
foreach($array as $i=>$k) {
if(strlen($result) > 0) {
$result .= ","
}
$result .= $i.'-'.$k;
}
echo $result;
try this code after foreach condition then echo $result1
$result1=substr($i, 0, -1);
Assuming the array is an index, this is working for me. I loop $i and test $i against the $key. When the key ends, the commas do not print. Notice the IF has two values to make sure the first value does not have a comma at the very beginning.
foreach($array as $key => $value)
{
$w = $key;
//echo "<br>w: ".$w."<br>";// test text
//echo "x: ".$x."<br>";// test text
if($w == $x && $w != 0 )
{
echo ", ";
}
echo $value;
$x++;
}
this would do:
rtrim ($string, ',')
see this example you can easily understand
$name = ["sumon","karim","akash"];
foreach($name as $key =>$value){
echo $value;
if($key<count($name){
echo ",";
}
}
I have removed comma from last value of aray by using last key of array. Hope this will give you idea.
$last_key = end(array_keys($myArray));
foreach ($myArray as $key => $value ) {
$product_cateogry_details="SELECT * FROM `product_cateogry` WHERE `admin_id`='$admin_id' AND `id` = '$value'";
$product_cateogry_details_query=mysqli_query($con,$product_cateogry_details);
$detail=mysqli_fetch_array($product_cateogry_details_query);
if ($last_key == $key) {
echo $detail['product_cateogry'];
}else{
echo $detail['product_cateogry']." , ";
}
}
$foods = [
'vegetables' => 'brinjal',
'fruits' => 'orange',
'drinks' => 'water'
];
$separateKeys = array_keys($foods);
$countedKeys = count($separateKeys);
for ($i = 0; $i < $countedKeys; $i++) {
if ($i == $countedKeys - 1) {
echo $foods[$separateKeys[$i]] . "";
} else {
echo $foods[$separateKeys[$i]] . ", \n";
}
}
Here $foods is my sample associative array.
I separated the keys of the array to count the keys.
Then by a for loop, I have printed the comma if it is not the last element and removed the comma if it is the last element by $countedKeys-1.

Categories