Check if a array have a value on specific positions - php

I'm getting the index keys of a haystack array containing many needles. The array contains another words too, but I don't need them to be checked.
So I'm using array_keys($haystack, &needle); to create an array containing the position of each needle.
Now I need to check in another array if on the positions from the array I've obtained by using array_keys I have a specific value. I need some ideas about how to do this.
The main idea:
$check = array_keys($haystack, &needle);
*now I need to check if I have a value on the positions from $check on $array2*
Then I need to do an action if it is found on a position (it doesn't matter on what position).

It'll work with this if it's an associative:
foreach($array1 as $k => $v)
{
if(isset($array2[$k]))
{
// Your thing
}
}
If you want to find based on the exact key index:
for($i = 0; $i < count($array1); $i++)
{
if($array1[$i] == "needle" && isset($array2[$i]))
{
if($array2[$i] == "goose")
{
// Your thing
}
}
}

You don't need to do array_keys();.
You can do it like this.
foreach ($haystack as $needle) {
if ($needle == $your_value) {
/* your stuff */
}
}

Related

How do I search if a value is in a range, inside a multi-dimensional array in PHP?

It's a simple question, but puzzling me:
$myarray = array(
array(10,20),
array(299, 315),
array(156, 199)
);
How do I check if given $x , lies in between, in any of those particular individual array values? I want to search each individual entry array.
For Example, I want to search, if $x is somewhere between: 10 to 20 and then between 299 to 315 and then between 156 to 199.
Try this:
function is_in_array_range($array, $search) {
foreach ($array as $value) {
$min = min($value);
$max = max($value);
if ($search >= $min && $search <= $max) {
return true;
}
}
return false;
}
$myarray = array(
array(10,20),
array(299, 315),
array(156, 199)
);
is_in_array_range($myarray, 9); // Returns false
is_in_array_range($myarray, 11); // Returns true
The function is_in_array_range() will take two arguments. The array, and the value you want to check is in the range.
When it enters, it will loop over all elements in the array. Every time it gets the highest and lowest value of the nested array (min() and max() function), and checks if the value you are looking for is between them. If this is the case, return true (this also stops the function). If true is never reached, the value is not found, so at the end of the function, return false.
this will do it code
foreach($myarray as $value)
{
if(in_array("10", $value, true))
{
echo "Got 10";
}
}

How to sort the merged arrays in php?

I have two arrays
using array_merge function, merged two arrays. Then I need to sort the merged array.
This is my php code
<?php
$file=file("master.bib");
$c=count($file);
//count of article
$key = '#article';
foreach ($file as $l => $line) {
if (strpos($line,$key) !== false) {
$l++;
$typeart[]= $l;
}
}//end-count of article
$key = '}';
foreach ($file as $l => $line) {
if (strpos($line,$key) === 0) {
$l++;
$typeclose[]= $l;
}
}
$p=array_merge($typeart,$typeclose);
echo sort($p);
?>
But am getting the output 1. I don't know what's wrong here.
As you can see from the sort() documentation, your array is a reference.
bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
// ^ & means reference
This means that your original array will be changed when the method is run. As you can also see by the documentation, it returns the following:
Returns TRUE on success or FALSE on failure.
So essentially (just like the example in the documentation) the correct use is:
sort($p); // $p will now be sorted
or the more verbose
if (sort($p)) {
// $p is now sorted
} else {
// $p could not be sorted for whatever reason
}
sort changes your array directly, so you should use print_r($p) to check the array like this:
sort($p); //Array Sorted and contents changed directly no return :)
print_r($p);

Check if array contains elements having elements of another array

$find=array('or','and','not');
$text=array('jasvjasvor','asmasnand','tekjbdkcjbdsnot');
I have to check if text array contains any of the elements find has. I'm able to do this for single text but don't know how to do it for all texts
$counter=0;
foreach($find as $txt){
if (strstr($text[0], $txt)) {
$counter++;
}
If i use this technique i'll have to run foreach number of times. Is there any other way to do this?
NOTE if array value contains or,and ,not not the whole word match
http://codepad.viper-7.com/VKBMtP
Input
$find=array('or','and','not');
$text=array('jasvjasvor','asmasn','tekjbdkcjbdsnot');
// array values "jasvjasvor" and "tekjbdkcjbdsnot" contains words `or,not`
Output
2 -> as two words from find array are contained in text array values
Use array_intersect():
if (count(array_intersect($find, $text)) >= 1) {
// both arrays have at least one common element
}
Demo.
UPDATE: If you're trying to find how many elements in $text array contain any of the values (partial match or whole-word match) in $find array, you can use the following solution:
$counter = 0;
foreach($find as $needle) {
foreach ($text as $haystack) {
if(strpos($haystack, $needle) !== false) $counter++;
}
}
echo $counter; // => 2
Demo.
$counter=0;
foreach($find as $txt){
foreach($txt as $value){
if (strstr($value, $txt)) {
$counter++;
}
}

Finding entry in array and putting it first or swapping with the first array entry

I have a PHP array full of arrays and what I want to do is search through this array for the chosen entry and swap it with the first entry in the array if that makes sense...
So for my example below I have chosen Penny so I would like her to either go before Bob or swap places with Bob.
My array looks like this:
$people = array(
array('Bob', 'Wilson'),
array('Jill', 'Thompson'),
array('Penny', 'Smith'),
array('Hugh', 'Carr')
);
I have tried using array_search but I don't think I am doing it correctly.
for ($i = count($array) - 1; $i > 0; $i--) {
if ($array[$i][0] == $first_name) { // Or by whatever you want to search? in_array...?
$searched_array = array_splice($array, $i, 1);
array_unshift($array, $searched_array[0]);
}
}
This is for prepending. If you want to swap, see the answer of #IAmNotProcrastinating
function swap (&$ary,$fromIndex,$toIndex=0)
{
$temp=$ary[$toIndex];
$ary[$toIndex]=$ary[$fromIndex];
$ary[$fromIndex]=$temp;
}
foreach ($elements as $key => $element) {
/* do the search, get the $key and swap */
}

php how to loop through array until condition is met?

I have a database table with images that I need to display. In my view, I'd like to display UP TO 10 images for each result called up. I have set up an array with the 20 images that are available as a maximum for each result (some results will only have a few images, or even none at all). So I need a loop that tests to see if the array value is empty and if it is, to move onto the next value, until it gets 10 results, or it gets to the end of the array.
What I'm thinking I need to do is build myself a 2nd array out of the results of the test, and then use that array to execute a regular loop to display my images. Something like
<?php
$p=array($img1, $img2.....$img20);
for($i=0; $i<= count($p); $i++) {
if(!empty($i[$p])) {
...code
}
}
?>
How do I tell it to store the array values that aren't empty into a new array?
you could do something like:
$imgs = array(); $imgs_count = 0;
foreach ( $p as $img ) {
if ( !empty($img) ) {
$imgs[] = $img;
$imgs_count++;
}
if ( $imgs_count === 10 ) break;
}
You can simply call array_filter() to get only the non-empty elements from the array. array_filter() can take a callback function to determine what to remove, but in this case empty() will evaluate as FALSE and no callback is needed. Any value that evaluates empty() == TRUE will simply be removed.
$p=array($img1, $img2.....$img20);
$nonempty = array_filter($p);
// $nonempty contains only the non-empty elements.
// Now dow something with the non-empty array:
foreach ($nonempty as $value) {
something();
}
// Or use the first 10 values of $nonempty
// I don't like this solution much....
$i = 0;
foreach ($nonempty as $key=>$value) {
// do something with $nonempty[$key];
$i++;
if ($i >= 10) break;
}
// OR, it could be done with array_values() to make sequential array keys:
// This is a little nicer...
$nonempty = array_values($nonempty);
for ($i = 0; $i<10; $i++) {
// Bail out if we already read to the end...
if (!isset($nonempty[$i]) break;
// do something with $nonempty[$i]
}
$new_array[] = $p[$i];
Will store $p[$i] into the next element of $new_array (a.k.a array_push()).
Have you thought about limiting your results in the sql query?
select * from image where img != '' limit 10
This way you are always given up to 10 results that are not empty.
A ẁhile loop might be what you're looking for http://php.net/manual/en/control-structures.while.php

Categories