php array variable - php

in my script,
$value= array("DK","Bloomsberry","McGrawHill","OXFORD","DC Books","Springer");
if(in_array("Bloomsberry",$value)){
echo "Bloomsberry is there inside the array";}
else{ echo "Bloomsberry is not there ";}
this works well
i have a variable $names which is a mysql result, which has data "DK","Bloomsberry","McGrawHill","OXFORD","DC Books","Springer" like an array data.
but when i place the variable inside like $value= array($names); instead of $value= array("DK","Bloomsberry","McGrawHill","OXFORD","DC Books","Springer"); , i am getting result "Bloomsberry is not there " instead of expected "Bloomsberry is there inside the array"

I suspect that the " signs get escaped and that also the array is passed as an single string. You will have to split the string to an array. If I where you I would submit to mysql: "DK,Bloomsberry,McGrawHill"etc and then do
<?php
$string = "DK,Bloomsberry,McGrawHill,OXFORD,DC Books,Springer";
$array = explode(",", $string);
if(in_array("Bloomsberry",$array)){
echo "Bloomsberry is there inside the array";}
else{ echo "Bloomsberry is not there ";}
The explode command returns an array split on the commas.
I hope this works for you

If $names is already an Array, then array($names) is an Array containing one element (the one element is your $names array).
If you want to assign $value to the array $names, you simply use the assignment operator:
$value = $names;
Then do your conditional in_array("Bloomsberry", $value);. Or you could just avoid the assignment and do in_array("Bloomsberry", $names).

Notice the following difference:
$value = array("DK","Bloomsberry","McGrawHill","OXFORD","DC Books","Springer");
print_r($value);
/* produces:
Array
(
[0] => DK
[1] => Bloomsberry
[2] => McGrawHill
[3] => OXFORD
[4] => DC Books
[5] => Springer
)
*/
where as:
$value = array("DK","Bloomsberry","McGrawHill","OXFORD","DC Books","Springer");
$newValue = array($value);
print_r($newValue );
/* produces:
Array
(
[0] => Array
(
[0] => DK
[1] => Bloomsberry
[2] => McGrawHill
[3] => OXFORD
[4] => DC Books
[5] => Springer
)
)
*/
in_array("Bloomsberry", $newValue) will only return true if "Bloomsberry" is a value in the first dimension of the array. However the only first dimension element in $newValue is the $value array.

Issue:
This is because in_array starts checking at the root node, and depending on how many levels the needle has depends in how many levels it checks within the haystack
An example of the above:
$a = array(array('p', 'h'), array('p', 'r'), 'o');
if (in_array(array('p', 'h'), $a))
{
echo "'ph' was found\n";
}
$a is actually 2 levels of arrays, also called multi-dimensional.
Within your code your placing your root level array, into another array, thus the array of the DB Then becomes array(array("results")) this when you check the first node using in_array("string") it cant find it within the root haystack.
Possible Fix:
Just use the actual result as your in_array check, example:
while($row = mysql_fetch_array($result))
{
/*
$row is a single dimension and can be used like so:
*/
if(in_array("Bloomsberry"),$row))
{
//Echo your success.
}
}

try this
$name = '"DK","Bloomsberry","McGrawHill","OXFORD","DC Books","Springer"';
$name = str_replace('"', '', $name);
$value = explode(',', $name);
Now your below given code will work.
if(in_array("Bloomsberry",$value)){
echo "Bloomsberry is there inside the array";}
else{ echo "Bloomsberry is not there ";}

Related

Php, array printing

I have an array:
Array (
[0] => Array (
[userid] => 5
[0] => 5
[firstname] => DALPA
[1] => DALPA
[lastname] => DALPA
[2] => DALPA
)
)
when i try to print this using foreach loop i get an error
<?php
include('../conn.php');
$q = $_GET['q'];
$adress = $conn->prepare("SELECT * FROM user WHERE firstname= :q ");
$adress->bindValue(':q', $q, PDO::PARAM_STR);
$adress->execute();
$result = $adress->fetchAll();
foreach($result as $item){
echo $item . "\n";
}
?>
Error:Array to string conversion in C:\xampp\htdocs\admin\adres\adres.php on line 13
Been asked many times but none of them solved my problem, what should I do?
php's echo statement can only echo strings. If it is not a string but a number for example, it will try to converse the given value to a string. With an array that is not possible.
In your case you are looping trough an array containing another array. As the error tells you, it fails to echo an array because it expects something that can be converted to a string.
So either use
foreach($result as $item) {
print_r($item) // or var_dump($item)
}
Or echo key => value pairs using
foreach($result as $item) {
echo $item['firstname'] . "\n";
echo $item['lastname'] . "\n";
... and so on
}
If you are expecting only one item to be returned, update your query by using fetch instead of fetchAll, which will return only one row.
You can then omit the unnecessary foreach loop.
And if you realy want to echo the array, you have to do the conversion manualy by using json_encode, which will convert the array to an JSON string.
echo json_encode( $result );

How to not echo array if previous one's key has been echoed already

This is what I get after a print_r($myArray) (wrapped in pre) on my array.
Array
(
[0] => 203.143.197.254
[1] => not/available
)
Array
(
[0] => 40.190.125.166
[1] => articles/not/a/page
)
Array
(
[0] => 25.174.7.82
[1] => articles/not/a/page
)
How would I return or echo just the first two in this case (no regex), given the fact that I would like to only output each array whose [1] value has not been echoed before?
My list as far more entries and $myArray[1] is sometimes the same, I want to skip echoing the same thing.
I have tried array_unique but I can't get it to work as param 1 is expected to be an array.
print_r(array_unique($myArray));
This works. Didn't do a full copy paste job but hopefully you get the idea of the logic
$echoed = array();
foreach($array as $arr) {
if(!in_array($arr[1],$echoed)) {
echo $arr[1];
$echoed[] = $arr[1];
}
}
$echoedBefore = array();
print_r(array_filter($myArray, function($entry) {
global $echoedBefore;
$alreadyEchoed = in_array($entry[1], $echoedBefore);
if (!$alreadyEchoed) {
$echoedBefore[] = $entry[1];
}
return !$alreadyEchoed;
}));

Removing elements from an array whose value matches a specified string

I have an array that looks like this:
Array ( [0] => Vice President [1] => [2] => other [3] => Treasurer )
and I want delete the value with other in the value.
I try to use array_filter to filter this word, but array_filter will delete all the empty values, too.
I want the result to be like this:
Array ( [0] => Vice President [1] => [2] => Treasurer )
This is my PHP filter code:
function filter($element) {
$bad_words = array('other');
list($name, $extension) = explode(".", $element);
if(in_array($name, $bad_words))
return;
return $element;
}
$sport_level_new_arr = array_filter($sport_level_name_arr, "filter");
$sport_level_new_arr = array_values($sport_level_new_arr);
$sport_level_name = serialize($sport_level_new_arr);
Can I use another method to filter this word?
array_filter() is the right function. Ensure your callback function has the correct logic.
Try the following:
function other_test($var) {
// returns whether the value is 'other'
return ($var != 'other');
}
$new_arr = array_filter($arr, 'other_test');
Note: if you want to reindex the array, then you could call $new_arr = array_values($new_arr); after the above.
foreach($sport_level_name_arr as $key => $value) {
if(in_array($value, $bad_words)) {
unset($sport_level_name_arr[$key])
}
}
This will create two arrays and will find the difference. In the second array we will put the elements to exclude:
array_values(array_diff($arr,array("other")));
If the callback function returns true, the current value from input is returned into the result array. PHP Manual
So you need to do return true; in your filter(); function instead of return $element; to make sure that no empty values are removed.

Find the key of a corresponding array value

I have an array like this. What i want is to get the value of the index for specific values. ie, i want to know the index of the value "UD" etc.
Array
(
[0] => LN
[1] => TYP
[2] => UD
[3] => LAG
[4] => LO
)
how can i do that??
array_search function is meant for that usage
snipet:
$index = array_search('UD', $yourarray);
if($index === false){ die('didn\'t found this value!'); }
var_dump($index);
Use array_search:
$array = array(0 => 'LN', 1 => 'TYP', 2 => 'UD', 3 => 'LAG', 4 => 'LO');
$key = array_search('UD', $array); // $key = 2;
if ($key === FALSE) {
// not found
}
Your best bet is:
array_keys() returns the keys, numeric and string, from the input array.
If the optional search_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the input are returned.
$array = array(0 => 'LN', 1 => 'TYP', 2 => 'UD', 3 => 'LAG', 4 => 'LO');
print_r(array_keys($array, "UD"));
Array
(
[0] => 2
)
Possible considerations for not using array_search()
array_search() If needle is found in haystack more than once, the first matching key is returned. To return the keys for all matching values, use array_keys() with the optional search_value parameter instead.
I suggest array_flip:
$value = "UD";
$new = array_flip($arr);
echo "result: " . $new[$value];
Just a note: some of these array_* functions are substantially more useful in PHP 5.3 with the addition of anonymous functions. You can now do things like:
$values = array_filter($userArray, function($user)
{
// If this returns true, add the current $user object to the resulting array
return strstr($user->name(),"ac");
});
Which will return all elements in our imaginary array of user objects that contain "ac" ("Jack","Jacob") in their name.
This has been possible in the past with create function, or simply by defining a function beforehand, but this syntax make it a lot more accessible.
http://ca2.php.net/manual/en/functions.anonymous.php
$array = Array(0 => LN, 1 => TYP, 2 => UD, 3 => LAG, 4 => LO);
$arrtemp = array_keys($array,'UD');
echo 'Result : '.$arrtemp[0];
I use array_keys to find it.

The PHP function array_unique doesn't work

I have an array in PHP and I want to remove duplicates.
I simply turned to the function array_unique() to create a new array and remove the duplicates.
Here's the code:
$unlink = array();
$unlink = array_unique($linkphoto);
foreach ($unlink as $link) {
echo $link, "<br />";
}
Still it shows duplicates! Any suggestions about what's wrong?
According to the documentation, the condition for equality is as follows:
Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same. The first element will be used.
What sort of data are you using? If two items aren't string equal, then they'll both remain in the array.
We need more context in order to be able to help you, like what the contents are of $linkphoto before array_unique is applied to it. For example:
<?php
$array = Array('A','B','C','D','B');
print_r($array); // Array ( [0] => A [1] => B [2] => C [3] => D [4] => B )
$result = array_unique($array);
print_r($result); // Array ( [0] => A [1] => B [2] => C [3] => D )
?>
As #nobody_ mentioned, it will only eliminate duplicates if their string representations are the same.

Categories