Search item in an array using PHP - php

I want to search an item like "January" or "February" in an array that looks like this
Array
(
[0] => January
[1] => February
[2] => March
[3] => April
)
This what I have tried so far. But not working.
if ( in_array("January", $date_array) ) {
echo "Found item in Array";
} else {
echo "Didn't find item in Array";
}
result:
Didn't find item in Array
This is the result of var_dump()
array(4) {
[0]=>
string(9) "January
"
[1]=>
string(10) "February
"
[2]=>
string(7) "March
"
[3]=>
string(7) "April
"
}

Don't know, where line breaks are coming from, but you can remove them, for example, with array_map:
$date_array = array_map('trim', $date_array);
// and then use `in_array`

Related

PHP Why two same value from two different string are not equal to each other

Why are these two strings not equal?
I tried to get the same name so I can create a file, however I cannot get two strings equal to each other, even though I think both strings have the same value.
I uploaded var_dump output
any idea how to fix it?
$selectCategory = scandir($_SERVER['DOCUMENT_ROOT'].'/database/');
$cat = explode('.',$category);
print_r($cat);
print_r($selectCategory);
if($cat[0] == $selectCategory[2]){
echo " true";
}
else{
echo "no";
}
output:
Array ( [0] => bus [1] => php )
Array ( [0] => . [1] => .. [2] => bus [3] => fruit )
no
This is var_dump output
array(2) { [0]=> string(5) " bus" [1]=> string(3) "php" }
array(4) { [0]=> string(1) "." [1]=> string(2) ".." [2]=> string(3) "bus" [3]=> string(5) "fruit" }
no
As you can see from the var_dump output the items you are comparing are different lengths. There is a space and possibly a hidden character in the $cat one:
To trim all space and some other characters use this:
$cat = array_map('trim', $cat);
$selectCategory = array_map('trim', $selectCategory);

Iterating through Array of Arrays generating unwanted output

I am having issues when iterating through an array of arrays in PHP.
I have the following array, which I have posted to the page using Ajax.
Array (
[0] => Array ( [0] => T64 [1] => Array ( [name] => T64 [dummyA] => 2 [dummyB]
=> 2 [dummyC] => 2 ) )
[1] => Array ( [0] => T65 [1] => Array ( [name] => T65 [dummyA] => 2 [dummyB]
=> 2 [dummyC] => 2 ) )
[2] => Array ( [0] => T91 [1] => Array ( [name] => T91 [dummyA] => 2 [dummyB]
=> 2 [dummyC] => 2 ) ) )
I have tried to print all of the inner values using the below method, however it always prints a T (on its own line), before each desired value.
foreach($sOptions as $row => $innerArray){
foreach($innerArray as $innerRow => $value){
print $value['dummyA'] . "<br/>";
print $value['dummyB'] . "<br/>";
print $value['dummyC'] . "<br/>";
}
}
Output:
T
T
T
2
2
2
T
T
T
2
2
2
T
T
T
2
2
2
Would anyone be able to give be some incite to where these T values are coming from?
It is obvious. You are trying to get indexed value of the actual value from second level array using a string index that does not exists.
Because any string can be accessed as an array then the non existing string index is interpreted as false so it returns first value, ie zero-index character from the string accessed as an array.
In first case the value T64 is actually accessed as array('T','6','1') so it returned T.
<?php
// simple example
// Get the first character of a string
$str = 'T64';
echo "First character is: ". $str[0] .PHP_EOL;
echo "Second character is: ". $str[1] .PHP_EOL;
echo "Third character is: ". $str[2] .PHP_EOL;
echo PHP_EOL;
echo "Applied to your code:". PHP_EOL;
$sOptions = Array ( Array ( 'T64' ) );
print_r($sOptions[0][0]['invalid string index']);
Look at the demo: https://eval.in/1063420
Output:
First character is: T
Second character is: 6
Third character is: 4
T
Note: turn on error reporting to simplify your debugging ;) How do I get PHP errors to display?
More reading about accessing strings as array in described in PHP manual Strings esspecialy Example #11 and later.
can you try to use only one foreach ? I haven't try this solution but you can try to do something of similar
foreach($sOptions as $row => $innerArray){
$value = $innerArray[1]
print $value['dummyA'] . "<br/>";
print $value['dummyB'] . "<br/>";
print $value['dummyC'] . "<br/>";
}
You can also use array_column to isolate the part you want to iterate.
foreach(array_column($arr,1) as $row => $value){
echo $value['dummyA'] . "\n";
echo $value['dummyB'] . "\n";
echo $value['dummyC'] . "\n";
}
This means the code will only iterate the following:
array(3) {
[0]=>
array(4) {
["name"]=>
string(4) "T64 "
["dummyA"]=>
string(2) "2 "
["dummyB"]=>
string(2) "2 "
["dummyC"]=>
string(2) "2 "
}
[1]=>
array(4) {
["name"]=>
string(3) "T65"
["dummyA"]=>
string(2) "2 "
["dummyB"]=>
string(2) "2 "
["dummyC"]=>
string(1) "2"
}
[2]=>
array(4) {
["name"]=>
string(4) "T91 "
["dummyA"]=>
string(2) "2 "
["dummyB"]=>
string(2) "2 "
["dummyC"]=>
string(2) "2 "
}
}
https://3v4l.org/YA6Vq

need to join arrays in to single one [duplicate]

This question already has answers here:
Combine two arrays
(11 answers)
Closed 5 months ago.
how can we join this two arrays into one array
for this, I had done my code like this and got the output as shown below
$groups_array = array_map('trim',explode(',', $tt));
$tt looks like this string(5) "11:00" string(5) "10:00"
array(1) { [0]=> string(5) "11:00" } array(1) { [0]=> string(5) "10:00" }
need desired output to look like
array(1) { [0]=> string(5) "11:00",[1]=> string(5) "10:00" }
My code is here please have a look
<?php $time_booked=$this->Hospital_model->get_already_booked_time($d,$timeslot->doctor_id);
foreach($time_booked as $index1=> $t) {
$tt=$t->time;
$groups_array = array_merge(array_map('trim',explode(',', $ttt)));
} ?>
my var_dump($time_booked) looks like this
array(2) { [0]=> object(stdClass)#40 (1) { ["time"]=> string(5) "11:00" } [1]=> object(stdClass)#41 (1) { ["time"]=> string(5) "10:00" } }
What about array_merge() with array_map()
$groups_array = array_merge(array_map('trim',explode(',', $tt)));
Output:-https://eval.in/1012484
By looking your edit in your question no need to do any extra stuff, just create an array and add values to it
<?php
$groups_array = []; //create array
$time_booked=$this->Hospital_model->get_already_booked_time($d,$timeslot->doctor_id);
foreach($time_booked as $index1=> $t) {
$groups_array[] =$t->time; //add values to array
}
var_dump($groups_array);
?>
What about array_merge ? That should give you the result.
http://php.net/manual/de/function.array-merge.php
EDIT:
$tt = ['11:00'];
$tt2 = ['10:00'];
$result = array_merge($tt,$tt2);
var_dump($result);
Result is
array(2) {
[0]=>
string(5) "11:00"
[1]=>
string(5) "10:00"
}
Is that not what you meant ?
Suppose you have two array which look like
$array1 = array(0 => "10:00 am");
$array2 = array(0 => "11:00 am");
and you want to join and want output like: Array ( [0] => 10:00 am [1] => 11:00 am )
then you can use array_merge option
$array3 = array_merge($array1, $array2);
If you print print_r($array3);
output will be
Array ( [0] => 10:00 am [1] => 11:00 am )

Simple array_diff not working

I have 2 arrays.
The first one is $teach_array and the second one is $langs_array.
Their respective values are:
$teach_array : Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
$langs_array : Array ( [0] => 2 [1] => 3 )
Im trying to return a new array containing all the entries from $teach_array that are not present in $langs_array.
So the end result should be: Array ( [0] => 1 [3] => 4 [4] => 5 )
I have tried using a couple of methods including :
Option 1
$result = array_diff($teachArray, $language_1d_array);
This still returns all the values of $teach_array.
Option 2
$result = array_diff_key($teachArray, $language_1d_array);
However, this only returns Array ( [2] => 3 [3] => 4 [4] => 5 ) which is not correct.
Option 3
$result = array_values(array_diff_key($teachArray, $language_1d_array));
This returns the same result as Option 2. I also tried using only array_diff instead of array_diff_key and it returns the same result as Option 1.
I did a var_dump on both of my arrays and here is the result.
$teach_array : array(5) { [0]=> string(5) " 1 " [1]=> string(5) " 2 " [2]=> string(5) " 3 " [3]=> string(5) " 4 " [4]=> string(5) " 5 " }
$lang_array : array(2) { [0]=> string(1) "2" [1]=> string(1) "3" }
hope you have already found the solution, but just in case I want to point you on following.
Blockquote
I did a var_dump on both of my arrays and here is the result.
$teach_array : array(5) { [0]=> string(5) " 1 " [1]=> string(5) " 2 " [2]=> string(5) " 3 " [3]=> string(5) " 4 " [4]=> string(5) " 5 " }
$lang_array : array(2) { [0]=> string(1) "2" [1]=> string(1) "3" }
No single value from $teach_array matches any value of $lang_array.
Because there are differently formatted values, one array contains whitespaces before and after the value you want to match " 2 ".
var_dump($teach_array) => array(5) { [0]=> string(5) " 4 " ... }
var_dump($lang_array) => array(5) { [0]=> string(1) "2" ... }
I guess you have some whitespaces included. Please try again with:
$diff = array_diff(array_map('trim', $teach_array), $lang_array);
PHPTester just tested yours, works fine for me..?
$teachArray =[1,2,3,4,5];
$langsarray =[2,3];
$result = array_diff($teachArray,$langsarray);
print_r($result);
works and prints 1, 4, 5 for me.
BUT...here's a solution for what you're trying to acquire: the values in teacher array that are not in langs
$new_array = array();
foreach($teach_array as $item){ // Loop the teacher_array
if(!in_array($item,$langs_array)){ // If the teach_array value doesn't exist in the lang_array, add the value
$new_array[] = $item;
}
}
I'm sure theres a more elegant way, but this works:
$teach = [1, 2, 3,4, 5];
$langs = [2, 3];
$result = [];
foreach ($teach as $key => $t) {
if (!in_array($t, $langs)) {
$result[$key] = $t;
}
}
var_dump($result);
This is (basically) what you say you have. It works for me:
<?php
$fred = array(0=>1, 1=>2, 2=>3, 3=>4, 4=>5);
$bert = array(0=>2, 1=>3);
$res = array_diff($fred, $bert);
print_r($res);

Sort array based on the numbers and a certain piece of text that occurs within a string

I have an array which I got from a directory with pdf files in it using scandir
$array = array(7) {
[0]=> string(17) "q150824-spost.pdf"
[1]=> string(17) "s150826-spost.pdf"
[2]=> string(16) "s150826-spro.pdf"
[3]=> string(17) "t150827-spost.pdf"
[4]=> string(16) "t150827-spro.pdf"
[5]=> string(17) "v150825-spost.pdf"
[6]=> string(16) "v150825-spro.pdf"
}
I need to sort the array by the numbers in the file name (eg. 150824 which is actually a date) which I can do using the following:
usort($array, function($a, $b) {
return filter_var($a, FILTER_SANITIZE_NUMBER_INT) - filter_var($b, FILTER_SANITIZE_NUMBER_INT);
});
The above gives me an array sorted by the numbers (which is almost what I want):
$array = array(7) {
[0]=> string(17) "q150824-spost.pdf"
[1]=> string(17) "v150825-spost.pdf"
[2]=> string(16) "v150825-spro.pdf"
[3]=> string(16) "s150826-spro.pdf"
[4]=> string(17) "s150826-spost.pdf"
[5]=> string(17) "t150827-spost.pdf"
[6]=> string(16) "t150827-spro.pdf"
}
However, in addition to this I would also like to sort alphabetically by spost and spro (the text before .pdf) I'm at a loss as to how to achieve this though?
If two strings in the array have the same numbers/date (eg. 150826) I want to then sort by spost first and then spro.
This should work for you:
First just grab the number and the topic name out of the file name with preg_match_all() and assign it to the variables. After this simply sort it by the topic, if the numbers are equal, otherwise by the numbers.
<?php
usort($arr, function($a, $b){
preg_match_all("/^\w(\d+)-(\w+)/", $a, $mA);
preg_match_all("/^\w(\d+)-(\w+)/", $b, $mB);
$numberA = $mA[1][0];
$numberB = $mB[1][0];
$topicA = $mA[2][0];
$topicB = $mB[2][0];
if($numberA == $numberB){
return strcmp($topicA, $topicB);
}
return $numberA > $numberB ? 1 : -1;
});
print_r($arr);
?>
output:
Array
(
[0] => q150824-spost.pdf
[1] => v150825-spost.pdf
[2] => v150825-spro.pdf
[3] => s150826-spost.pdf
[4] => s150826-spro.pdf
[5] => t150827-spost.pdf
[6] => t150827-spro.pdf
)
Actually you can just do the following
$array =[
"q150824-spost.pdf",
"s150826-spost.pdf",
"s150826-spro.pdf",
"t150827-spost.pdf",
"t150827-spro.pdf",
"v150825-spost.pdf",
"v150825-spro.pdf",
];
usort($array, function($a, $b) {
return filter_var($a, FILTER_SANITIZE_NUMBER_INT) - filter_var($b, FILTER_SANITIZE_NUMBER_INT) + (strlen($b) > strlen($a) ? 1 : 0);
});
print_r($array);
Output
Array
(
[0] => q150824-spost.pdf
[1] => v150825-spost.pdf
[2] => v150825-spro.pdf
[3] => s150826-spost.pdf
[4] => s150826-spro.pdf
[5] => t150827-spost.pdf
[6] => t150827-spro.pdf
)
It is sort by spost first and then spro

Categories