String to an array and then foreach - php

I have a variable string which is passed to an and array then foreach that just does not want to work. Below is the code im using.
$explode = $_obj->getModDependencies();
//this variable will returns/echos the string as #ModA,#Mod_b,#Mod3 etc (yes # is in each value)
and the foreach and array php code im using
$arr = array($explode);
foreach ($arr as $value) {
echo ''.$value.'';
}
if i use the above code it echos one hyperlink with each value at the end of it (http://myurl/mod?mod_id=#ModA,#Mod_b,#Mod3) but i want to echo each hyperlink for each value.
Which would be
http://myurl/mod?mod_id=#ModA
http://myurl/mod?mod_id=#Mod_b
and so forth.
But if i place the actual variable output string directly into the array it echos out how i want it (see below code that works)
$arr = array(#ModA,#Mod_b,#Mod3);
foreach ($arr as $value) {
echo ''.$value.'';
}
Any help wold be awesome!!

$arr = array($explode);
Thats the issue, just by saying something is within array() doesnt really make it an array as you expect it to be. You only gave it 1 argument.
You also mentioned the value of $explode is like this #ModA,#Mod_b,#Mod3. Just by naming something $explode doesn't explode it. You have to explode it yourself
$arr=explode(",","#ModA,#Mod_b,#Mod3");
//$arr=explode(",",$explode) in your case
Once that is done, your loop is already fine
foreach ($arr as $value) {
echo ''.$value.'';
}
Fiddle

When your variable $explode will be a string as '#ModA,#Mod_b,#Mod3' then you have to explode it.
$arr = explode(',', $explode);
foreach ($arr as $value) {
echo ''.$value.'';
}

Related

Foreach only showing last item in array [duplicate]

This question already has answers here:
Array Foreach Loop Prints Last Item Only [closed]
(4 answers)
Closed 9 months ago.
I'm attempting to make a foreach loop to iterate over each item in an array, but it only captures the last item and does not iterate over the first one. I've stripped down the code to only show the relevant parts and added some commands to identify the problem as described above.
$message == "kk,ll";
$myArray = explode(',', $message);
print_r ($myArray);
foreach ($myArray as $value);
{
echo "$value <br>";
$array[] = $value;
}
print_r ($array);
The output is:
Array ( [0] => kk [1] => ll ) ll
Array ( [0] => ll )
You can see that when I use print_r() the array contains two items. But the foreach loop only loops over the last item. Adding the array elements into a new array inside the loop also ends up with an array containing only the last element. What am I doing wrong?
You have two mistakes in you code:
In your first line you have two equal signs which should only be one.
In your foreach loop, you have by mistake put an semicolon at the end:
foreach ($myArray as $value);
Doing this, the foreach loop will run, but the code inside the {} is actually placed outside the foreach loop, and thereby causing $value only to store the last element of the array.
The code should look like this:
$message = "kk,ll";
$myArray = explode(',', $message);
print_r ($myArray);
foreach ($myArray as $value) {
echo "$value <br>";
$array[] = $value;
}
print_r ($array);
your foreach just assigned the $value, but output nothing. This is caused by the ; after foreach, same as
foreach ($myArray as $value)
{}
And after this, the $value have the last element of $myArray, then
{
echo "$value <br>";
$array[] = $value;
}
only output the last element.
remove the ; after the Foreach like in the follow code
foreach ($myArray as $value)
{
echo "$value <br>";
$array[] = $value;
}
In Laravel Framework Use Code into Controller:
$dd = $categories->pluck( 'title' )->toArray();
foreach ( $dd as $key => $value ) {<br />
$array[$key] = '.' . $value;<br />
} <br />
$cat = implode( ',' , $array );
<br />
// Result Display : James,Mark,Helmet.....
Only remove the semicolon after foreach ($myArray as $value) or used it

make the data into an array and get the values

I have the data in my table like this
Arabic,Assamese,Azerbaijani,Belarusian
I want to show the data in an array so that I can use foreach and get the values for the array. So can someone tell me how to make it as an array and get values?
$string = "Arabic,Assamese,Azerbaijani,Belarusian";
$language_array= explode(',',$string);
Supposing you have perform the query to the database and already has the data you can use explode function. See this DEMO.
$data = $row['data_from_table']; //your data is Arabic,Assamese,Azerbaijani,Belarusian
$exp = explode(",", $data);
foreach ($exp as $value){
echo $value;
echo PHP_EOL;
}
?>
Use explode function
$database_value = $db['your_data'];
$value_array = explode(',',$database_value);
print_r($value_array);
foreach ($value_array as $value){
echo $value.'<br>';
}

Convert a string to an array in PHP

I have an array like such:
array('some_key' => 'some_value');
I would like to take that and transform it to, this should be done programatically
array('some_key' => array('some_value'));
This should be rather simple to do but the only think I can find is answers on string split and explode, to explode strings into arrays. I thought PHP, like other languages, had something called to_array or toArray.
I am assuming this is super easy to do?
If you're just doing the one array element, it's as simple as:
$newarray['some_key'] = array($sourcearray['some_key']);
Otherwise if your source array will have multiple entries, you can do it in a loop:
foreach($sourcearray AS $key => $value) {
$newarray[$key] = array($value);
}
Something as simple as $value = array($value) should work:
foreach ($array as &$value) {
$value = array($value);
}
unset($value); //Remove the reference to the array value
If you prefer to do it without references:
foreach ($array as $key => $value) {
$array[$key] = array($value);
}
You can try like this
<?php
$arr=array('some_key' => 'some_value');
foreach($arr as $k=>$v)
{
$newarr[$k] = array($v);
}
var_dump($newarr);

is it possible to use regex to search inside an array using php

I have an array of string i need to search an string inside the array using regex is it possible if so please explain..
$a = preg_grep("/search_word/",$array_of_strings);
print_r($a);
You can use a foreach loop to loop through all the elements and use a preg_match on each of them. If it matches, add it to an array of matches.
foreach($array as $check) {
if (preg_match("/expression/", $check)) $matches[] = $check;
}
Very simple example.
You can iterate through the array using a foreach loop and search for the key in each element. An example:
<?php
$days = array('Sunday','Monday','Tuesday');
$key = "Sunday";
foreach($days as $day) {
if(preg_match("/$key/",$day)) {
echo "Key $key found !!";
}
}
?>

Exploding Arrays in PHP While Keeping the Original Key

How can I do the following without lots of complicated code?
Explode each value of an array in PHP (I sort of know how to do this step)
Discard the first part
Keep the original key for the second part (I know there will be only two parts)
By this, I mean the following:
$array[1]=blue,green
$array[2]=yellow,red
becomes
$array[1]=green //it exploded [1] into blue and green and discarded blue
$array[2]=red // it exploded [2] into yellow and red and discarded yellow
I just realized, could I do this with a for...each loop? If so, just reply yes. I can code it once I know where to start.
given this:
$array[1] = "blue,green";
$array[2] = "yellow,red";
Here's how to do it:
foreach ($array as $key => $value) {
$temp = explode(",", $value, 2); // makes sure there's only 2 parts
$array[$key] = $temp[1];
}
Another way you could do it would be like this:
foreach ($array as $key => $value) {
$array[$key] = preg_replace("/^.+?,$/", "", $value);
}
... or use a combination of substr() and strpos()
Try this:
$arr = explode(',','a,b,c');
unset($arr[0]);
Although, really, what you're asking doesn't make sense. If you know there are two parts, you probably want something closer to this:
list(,$what_i_want) = explode('|','A|B',2);
foreach ($array as $k => &$v) {
$v = (array) explode(',', $v);
$v = (!empty($v[1])) ? $v[1] : $v[0];
}
The array you start with:
$array[1] = "blue,green";
$array[2] = "yellow,red";
One way of coding it:
function reduction($values)
{
// Assumes the last part is what you want (regardless of how many you have.)
return array_pop(explode(",", $values));
}
$prime = array_map('reduction', $array);
Note: This creates a different array than $array.
Therefore $array == $prime but is not $array === $prime

Categories