Find a specific value from an exploded array - php

Hello so I have exploded a row from my database, I want to find a specific value based on the exploded array.
My row example.
Josh Johnson|Jenny Launcher|Easter Fonter|Eric Bennett
Here is my code:
<?php
$rowexplode = $row['name'];
$a = explode("|",$rowexplode);
if(count($a)>1) {
$explode_results = $rowexplode;
$explode_array = str_replace("|",", ", $explode_results);
echo $explode_array;
}
else {
echo "";
}
?>
This is what it shows
Josh Johnson, Jenny Launcher, Easter Fonter, Eric Bennett
Now I would like it to grab one of those names and display it.
For example. Grab Easter Fonter from the list and echo something like "Easter Fonter was here".
I don't know if it's possible to specify a specific name out of the exploded array.

You can use in_array function to check. Since you already have data in array $a
if(in_array("Easter Fonter", $a))

It helps to know what you've created at each step of the way:
<?php
$rowexplode = $row['name']; // $rowexplode is now a string
$a = explode("|",$rowexplode);
// $a is an array with strings, such as:
// array('Josh Johnson, 'Jenny Launcher', 'Easter Fonter', 'Eric Bennett')
if(count($a)>1) {
$explode_results = $rowexplode;
// $explode_results is now just a copy of $rowexplode, still just a string
$explode_array = str_replace("|",", ", $explode_results);
// This says array, but it isn't. It's just a string with the pipes replaced:
// "Josh Johnson, Jenny Launcher, Easter Fonter, Eric Bennett"
echo $explode_array;
// Output that string
}
So, if you want the values, you could do:
foreach ($a as $name) {
echo "$name was here\n"; // Echo each name one at a time
}

$arr = ["Josh Johnson", "Jenny Launcher", "Easter Fonter", "Eric Bennett"];
foreach($arr as $name) {
if($name == "Easter Fonter") {
echo $name + " was here";
}
}

This may helpful
//your text here
$rowexplode = 'Josh Johnson|Jenny Launcher|Easter Fonter|Eric Bennett';
$a = explode("|",$rowexplode);
if(count($a)>1) {
//your search string
$name = "Easter Fonter";
//check here
if(in_array($name,$a))
{
echo $name." was here.";
}else{
echo "Name Not Found".implode(', ', $a);
}
}
else {
echo "";
}
?>

Related

How to echo an array only if it has values in php?

I run a foreach loop, where some of the loops contain nothing into the following variables, they are empty.
However, the "hi world" is echoed always.
How can I show the "hello world" only if at least one of the $row['utm_source'],$row['utm_medium'],$row['utm_campaign'] has a value?
$arr = array($row['utm_source'],$row['utm_medium'],$row['utm_campaign']);
if (!empty($arr)) {
echo "hi world";
}
You an do it using count() and array_filter() :-
$arr = array($row['utm_source'],$row['utm_medium'],$row['utm_campaign']);
if (count(array_filter($arr))>0) {
echo "hi world";
}
You can use two methods:
1. implode + trim
implode joins the array items if they are strings together with the provided delimiter.
if( trim(implode("", $arr)) !== ""){
echo "hi world";
}
2. array_filter
array_filter returns the items which returns true to the provided callback function.
$arr = array_filter($arr, function($d) { return trim($d) !== ""; });
if(count($arr)){
echo "hi world";
}
Here is a rough way you can do it
<?php
$row = array();
$row['utm_source'] = null;
$row['utm_medium'] = null;
$row['utm_campaign'] = 1;
foreach ($row as $key => $value) {
if(isset($key)){
echo 'Hello';
break;
}
}
Here's the eval link
Also you can check it by
if (!empty($row['utm_source'])) {...}

PHP strpos() and str_replace()

I got a problem with my small php script.
My code should function as a follow-/unfollow-system like in forum softwares (for example XenForo).
So what my script does is that it searches for a user in a string and if the name is found it removes the name of the user in the string. But my problem is that the script can not search for the name and comma for some reason because I try to remove the comma from the string aswell.
Any help is appreciated, thanks in advance :)
Example:
Peter is following Franz and George but he want's to unfollow George
Script:
<?php
$user1 = "Peter";
$following1 = "Franz, George";
$user2 = "Franz";
$following2 = "Peter, George";
$user3 = "George";
$following3 = "Peter, Franz";
//
//
//
if (strpos($following1, $user3) == true) {
echo "Can remove follow.";
if (strpos($following1, ", $user3")) {
$user3 = ", $user3";
$fNew = str_replace($user3, "", $following1);
echo "$fNew<br>";
} else if (strpos($following1, "$user3, ")) {
$use3 = "$user3, ";
$fNew = str_replace("$user3", "", $following1);
echo "$fNew<br>";
}
} else if ($following1 == $user3) {
echo "Can remove follow.";
$fNew = str_replace($user3, "", $following1);
echo "$fNew<br>";
} else {
echo "Can't remove follow";
}
?>
Have a look a this:
<?php
$follow = "Peter, Franz, Spongebob";
$guyToUnfollow = 'Franz';
$people = explode(',', $follow);
var_dump($people);
foreach ($people as $key => $person) {
$person = trim($person);
if ($person == $guyToUnfollow) {
unset($people[$key]);
}
}
$follow = implode(',',$people);
var_dump($follow);
Firstly, we convert the CSV to an array, then loop through it. We use trim to remove whitespace, and unset any value in the array that matches the guy you want to unfollow. Finally, we recreate the csv using implode.
See it working here https://3v4l.org/QEnHj
strpos returns the position of the string, so you need to check if its not false in stead of checking if its true.
So you should use:
strpos($following1, $user3) !== false

check characters are available or not in array

I have two variables such as below
$string1 = array('A','b','c');
$string2 = 'bAcdadbcliek'
need to check all the characters from string1 is presents in string2 or not in php and values are dynamic.
try This
<?php
$string1 = array('A','b','c','2');
$string2 = 'bAcdadbcliek';
foreach($string1 as $newstring)
{
$finalval=strrchr($string2,$newstring);
if($finalval!="")
{
echo $newstring." ---: Available in given String<br/>";
}
else
{
echo $newstring." ---: Not Available in given String<br/>";
}
}
?>
use str_split and array_intersect
<?php
$string1 = array('A','b','c');
$string2 = 'bAcdadbcliek';
$new = str_split($string2);
$new_2 = array_intersect($string1,$new);
if(count($new_2)==count($string1))
{
echo "all matched";
}
else
{
echo "not ";
}
?>
The following function will return a boolean true/false if all values are matched. It is case-sensitive.
Basically, split $string2 into an array and intersect it, match the count of that against the count of $string1 (which is an array, not a string by the way). If the count is equal, everything was found.
$string1 = array('A','b','c');
$string2 = 'bAcdadbcliek';
function match_string(string $string, array $match_values) {
if (count(array_intersect(str_split($string), $match_values)) == count($match_values))
return true;
return false;
}
Live demo

PHP foreach loop messes up my in_array function

I've written a script that checks bulk input of names received via a textarea and omits all values that are already in the database. It works if you enter just one repeated name. If you enter two or more, it will filter out the first repeated name, treat the rest as unique names and insert them in the database. I can't figure out why.
Firstly, this is an array that is built in another part of the script. It's generated from a database query:
Array
(
[0] => john
[1] => peter
[2] => max
[3] => jake
)
This array is referred to as $onlyHandles. Then this is the script:
if((isset($_POST['extract']) && !empty($_POST['extract']))){
$handles = trim($_POST['extract']);
$handles = explode("\n", $handles);
if(count($handles)>200){
echo 'error';
exit(1);
}
foreach($handles as $handle) {
$handleRep = strtolower(str_replace('#','',$handle));
$handleClean = str_replace(str_split('\\/:*?&"<>=+-#%$|'), ' ', $handleRep, $count);
if ($count > 0) {
echo 'error';
exit(1);
}
else{
if (in_array($handleClean, $onlyHandles)){
$delmessage .= "<p>".$handleClean." is already in your list.</p>";
}
else{
$sqlIns = "INSERT INTO...blah blah blah)";
$resultIns = mysql_query($sqlIns);
$resInsArr[] = array($resultIns);
}
}
}
$countresIns = count($resInsArr);
if ($countresIns > 0){
$delmessage .= "<p>User(s) added to list succesfully!</p>" ;
}
}
Now, if you enter "john" in the textarea, it will shout that the name already exists. If you enter "john" and "max" it will omit john and add max.
Any help would be greatly appreciated.
P.S. regarding the query format, I know, I know, thanks!
I would like to give U some idea about how to achieve it:
Replace the first line:
if((isset($_POST['extract']) && !empty($_POST['extract']))){
through
if((!empty($_POST['extract']))){
because !empty already guives U the guaranty that it isset
I am suspescting some special chars in play
U could also use the power of Regular Expression to replace the unneeded chars
in replacing:
Line 12: $handleClean = str_replace(str_split('\\/:*?&"<>=+-#%$|'), ' ', $handleRep, $count);
Through:
$handleClean = preg_replace("/\[\/:\*?&\"<>=\+-#%\$\|\]*/", ' ', $handleRep, $count);
In Ur For-Loop, what about refactoring the following lines:
line 2: $handles = trim($_POST['extract']);
through (trim is not necessary hier)
$handles = $_POST['extract'];
AND
line 11: $handleRep = strtolower(str_replace('#','',$handle));
through
$handleRep = trim(strtolower(str_replace('#','',$handle)));
Hey ;-),
U should also add some print_r(...) to debug each step
thanks #Ulrich Tevi Horus that made my code a bit cleaner but didn't solve the mysteriously disappearing users.
#shulard, you should post this as an answer to get the upvote. array_diff was indeed the best solution.
Here's the final code. Needs some tidying up but it's good enough to go on my server for testing.
//this is the current contents of the list:
$onlyHandles = array();
foreach ($organizedArray as $key2 => $val2) {
$onlyHandles[] = $val2['name'];
}
echo "<br>begin onlyhandles<br>";
print_r($onlyHandles);
echo "<br>end onlyhandles<br>";
//finish preparation for display
//if names submitted for the list list
if(!empty($_POST['extract'])){
$handles = trim($_POST['extract']);
$handles = explode("\n", $handles); //this is now an array
echo "<br>begin handles<br>";
print_r($handles);
echo "<br>end handles<br>";
//$countInput = count($handles);
if($countInput>200){
echo '<p style="color:red;">Please Enter fewer than 200 names!</p>';
exit(1);
}
else{
$handleFinal = array();
foreach($handles as $handle) {
//$handleRep = strtolower(str_replace('#','',$handle));
$handleRep = trim(strtolower(str_replace('#','',$handle)));
$handleClean = str_replace(str_split('\\/:*?&"<>=+ -#%$|'), 'p', $handleRep, $count);
//$handleClean = preg_replace("/\[\/:\*?&\"<>=\+-#%\$\|\s+\]*/", ' ', $handleRep, $count);
echo "handleClean: ".$handleClean."<br>";
if ($count > 0) {
echo '<p style="color:red;">Your input contained special characters.</p>';
exit(1);
}
else{
$handleFinal[] = $handleClean;
}
}//end foreach
}//finish checking count input number
echo "<br>begin handleFinal<br>";
print_r($handleFinal);
echo "<br>end handleFinal<br>";
$countFinal = count($handleFinal);
echo "<br>countfinal is ".$countFinal."<br>";
//check if this user is already in the list
$handleDiffs = array_diff($handleFinal,$onlyHandles);
echo "<br>begin handlediffs<br>";
print_r($handleDiffs);
echo "<br>end handlediffs<br>";
foreach($handleDiffs as $handleDiff) {
$sqlIns = "blah blah blah";
$resultIns = mysql_query($sqlIns);
$resInsArr[] = array($resultIns);
}
$countresIns = count($resInsArr);
if ($countresIns > 0){
$delmessage .= "<p>User(s) added to the list succesfully!</p>" ;
}
}
I post my comment answer as a real answer :)
You must trim your $handle variable too because it's possible to have some spaces around it...
Then about your problem, I don't understand it. Your code seems "clean", maybe you should consider set the strict flag to true see function definition here.

how coding to check the data with array Intersect?

I wanted to check to enter data into the database.Checks are as follows
$implode1 = "apple, orange, banana";
$implode2 = "banana, mango";
If the banana in the variable $implode1 is also contained in the variable $implode2, it should display a warning message.
and if the value of the variable is empty, then the execution will be ignored. example:
$implode1 = "";
$implode2 = "";
How to code for the above problem?
Help me please :(
$implode1 = "apple, orange, banana";
$implode2 = "banana, mango";
$implode1Array = explode(", ", $implode1);
$implode2Array = explode(", ", $implode2);
$result = array_intersect($implode1Array, $implode2Array);
if(count($result) > 0) {
exit('Error!');
}
Typically I would assume that by cat you mean concatenation, but it doesn't seem proper here. But, assuming that is what you mean, you would just check for the same concatenation character (a comma) in both variables, like so:
if ( stristr($implode1, ",") && stristr($implode2, ",") ) {
// error
} else {
// success, do something
}
However, assuming you mean the same item being entered in both variables, in this case fruit, you can check it this way:
$im1 = explode(",", $implode1);
$im2 = explode(",", $implode2);
foreach($im1 as $i) {
if ( array_search($i, $im2) ) {
// error
} else {
// success, do something
}
}
You could of course just search both strings for a given value, but I don't think that's what you're going for. But assuming it is, here is that code:
$duplicate = "apple"; // the item you are searching for a duplicate of
if ( stristri($implode1, $duplicate) && stristr($implode2, $duplicate) ) {
// error
} else {
// success, do something
}
if (count(array_intersect)) { /* warning */ }
You can use PHP's array_intersect function to get the intersection (see http://php.net/manual/en/function.array-intersect.php):
$arr1 = explode(", ", "apple, orange, banana");
$arr2 = explode(", ", "banana, mango");
$intersection = array_intersect($arr1, $arr2);
if (count($intersection) > 0) {
echo "WARNING: the lists have a non-empty intersection!";
}

Categories