check inside array if the value sperated by comman [duplicate] - php

This question already has answers here:
How to explode an array into another array and not subarray using PHP?
(3 answers)
Closed 9 months ago.
Results in array as below,
How can I convert the above array as below:
array:3[
0=>"11856"
1=>"12235"
2=>"11843"
So if any value is separated by comma, remove from that index array and add another index with removed value.
I have tried logic as below:
foreach($domains as $row){
$domain = explode(',',$row);
$row = $domain;
}
No Luck, Any better approach?
Hope make sense. Thanks in advance for all.

Just loop through your source array and explode it with , character. And after explode it return Array, just loop this array push it add to your return array
function convert_array($data) {
$ret = array();
foreach($data as $d) {
$tmp = explode(',', $d);
foreach($tmp as $t) {
$ret[] = $t;
}
}
return $ret;
}
$data = array("11856,12235,113", "11843");
var_dump(convert_array($data));
and output is
array(3) {
[0] => 11856
[1] => 12235
[2] => 113
[3] => 11843
}

Thanks for all your answers,
I manage to achieve the requirement just in one line of code as below.
$domain = explode(",",implode(",",$domains));
First Implode by comma, Then explode the result. Done the magic.

I have a solution as per your question. This is very simple and easy solution. I used your code for solve your problem.
$domains = array(0=>"11856,12235", 1=>"11843");
foreach($domains as $row){
$domain = explode(',',$row);
foreach($domain as $d){
$a[] = $d;
}
}
echo '<pre>';
print_r($a);
Result:
Array
(
[0] => 11856
[1] => 12235
[2] => 11843
)

Related

PHP array get current element

I have an interesting task which can not handle. I have an PHP array that is generated automatically and randomly once a multi-dimensional, associative or mixed.
$data['sport']['basketball']['team']['player']['position']['hand']['name']['finalelement']
$data['sport']['basketball']['team']['player'][0]['position']['hand']['name']['finalelement']
$data['sport']['basketball']['team']['player'][0]['position']['hand']['name'][0]['finalelement']
$data['sport']['basketball']['team']['player']['position']['hand']['name'][0]['finalelement']
The goal is, no matter whether it is multidimensional or associative get to the final element. There is a simple way that has few if conditions. But I want to ask if you have an idea if there is any more intreresen way?
you may use array_walk_recursive as follows :
$data['sport']['basketball']['team']['player']['position']['hand']['name']['finalelement'] = 'e1';
$data['sport']['basketball']['team']['player'][0]['position']['hand']['name']['finalelement'] = 'e2';
$data['sport']['basketball']['team']['player'][0]['position']['hand']['name'][0]['finalelement'] = 'e3';
$data['sport']['basketball']['team']['player']['position']['hand']['name'][0]['finalelement'] = 'e4';
$list = [];
array_walk_recursive($data, function ($value, $key) use (&$list) {
$list[] = $value;
});
print_r($list);
This will Output the following:
Array (
[0] => e1
[1] => e4
[2] => e2
[3] => e3
)
Next code returns first deepest value that is not an array:
$data['sport']['basketball']['team']['player']['position']['hand']['name'][0]['finalelement'] = 'end';
$current = $data;
while (is_array($current)) {
$current = array_values($current)[0];
}
print $current; // end

PHP: How to delete all array elements after an index [duplicate]

This question already has answers here:
php - how to remove all elements of an array after one specified
(3 answers)
Closed 9 years ago.
Is it possible to delete all array elements after an index?
$myArrayInit = array(1=>red, 30=>orange, 25=>velvet, 45=>pink);
now some "magic"
$myArray = delIndex(30, $myArrayInit);
to get
$myArray = array(1=>red, 30=>orange);
due to the keys in $myArray are not successive, I don't see a chance for array_slice()
Please note : Keys have to be preserved! + I do only know the Offset Key!!
Without making use of loops.
<?php
$myArrayInit = [1 => 'red', 30 => 'orange', 25 => 'velvet', 45 => 'pink']; //<-- Your actual array
$offsetKey = 25; //<--- The offset you need to grab
//Lets do the code....
$n = array_keys($myArrayInit); //<---- Grab all the keys of your actual array and put in another array
$count = array_search($offsetKey, $n); //<--- Returns the position of the offset from this array using search
$new_arr = array_slice($myArrayInit, 0, $count + 1, true);//<--- Slice it with the 0 index as start and position+1 as the length parameter.
print_r($new_arr);
Output :
Array
(
[1] => red
[30] => orange
[25] => velvet
)
Try
$arr = array(1=>red, 30=>orange, 25=>velvet, 45=>pink);
$pos = array_search('30', array_keys($arr));
$arr= array_slice($arr,0,$pos+1,true);
echo "<pre>";
print_r($arr);
See demo
I'd iterate over the array up until you reach the key you want to truncate the array thereafter, and add those items to a new - temporary array, then set the existing array to null, then assign the temp array to the existing array.
This uses a flag value to determine your limit:
$myArrayInit = array(1=>'red', 30=>'orange', 25=>'velvet', 45=>'pink');
$new_array = delIndex(30,$myArrayInit);
function delIndex($limit,$array){
$limit_reached=false;
foreach($array as $ind=>$val){
if($limit_reached==true){
unset($array[$ind]);
}
if($ind==$limit){
$limit_reached=true;
}
}
return $array;
}
print_r($new_array);
Try this:
function delIndex($afterIndex, $array){
$flag = false;
foreach($array as $key=>$val){
if($flag == true)
unset($array[$key]);
if($key == $afterIndex)
$flag = true;
}
return $array;
}
This code is not tested

Remove array elements based on value supplied

If I had an array like this...
array('1','2','3','4','10')
... how could I remove elements before the element whose value I supply.
For example:
If I supplied 1 then array = (1,2,3,4,10)
If it were 2 then array = (2,3,4,10) //Remove the numbers before 2
If it were 3 then array = (3,4,10) //Remove the numbers before 3
If it were 4 then array = (4,10) //Remove the numbers before 4
If it were 10 then array = (10) //Remove all before the 10
I'm currently thinking of doing with using if else. But is there a way to do this using some kind of php array function itself.
Make use of array_search and array_slice
<?php
$arr=array_slice($arr, array_search('4',array('1','2','3','4','10')));
print_r($arr);
OUTPUT :
Array
(
[0] => 4
[1] => 10
)
Demo
Maybe this would help:
$myArray = array('1','2','3','4','10');
$x=3;
$myArray = array_splice($myArray, array_search($x, $myArray), count($myArray));
$myArray = array('1','2','3','4','10');
$value = 3;
$key = array_search($value, $myArray);
$myNewArray = array_splice($myArray, 0, $key);
$array = array_filter($array, function($item) use ($filterItem) {
return $item !== $filterItem;
});
Will filter out every item equal to $filterItem. array_filter on php.net

How can you sort each element inside of an array alphabetically [duplicate]

This question already has answers here:
PHP: How to sort the characters in a string?
(5 answers)
Closed 8 years ago.
For example we have the following words: hey, hello, wrong
$unsorted = array("eyh", "lhleo", "nrwgo");
I know that I could use asort to sort the array alphabetically, but I don't want that.
I wish to take the elements of the array and sort those, so that it would become something like this:
$sorted = array("ehy", "ehllo", "gnorw"); // each word in the array sorted
hey sorted = ehy
hello sorted = ehllo
wrong sorted = gnorw
As far as I know, the function sort will only work for arrays, so if you attempt to sort a word using sort, it will produce an error. If I had to assume, I will probably need to use a foreach along with strlen and a for statement or something similar, but I am not sure.
Thanks in advance!
function sort_each($arr) {
foreach ($arr as &$string) {
$stringParts = str_split($string);
sort($stringParts);
$string = implode('', $stringParts);
}
return $arr;
}
$unsorted = array("eyh", "lhleo", "nrwgo");
$sorted = sort_each($unsorted);
print_r($sorted); // returns Array ( [0] => ehy [1] => ehllo [2] => gnorw )
$myArray = array("eyh", "lhleo", "nrwgo");
array_walk(
$myArray,
function (&$value) {
$value = str_split($value);
sort($value);
$value = implode($value);
}
);
print_r($myArray);
Try this
$unsorted = array("eyh", "lhleo", "nrwgo");
$sorted = array();
foreach ($unsorted as $value) {
$stringParts = str_split($value);
sort($stringParts);
$sortedString = implode('', $stringParts);
array_push($sorted, $sortedString);
}
print_r($sorted);

php - how to use multiple array in foreach [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
foreach with three variables add
i have following code i want to use multiple array in foreach. please note that i need $yourSiteContent[] as it is.
foreach ($pieces as $id and $pieces1 as $id_date) {
$yourSiteContent[] = array('permalink' => $id, 'updated' => $id_date);
}
as you can see i have two arrays ($pieces and $pieces1), please check a loop and let me know where i am doing mistake.
$pieces1 contains dates and $pieces contains urls.
thanks for your help.
Assuming both $pieces and $pieces1 have the same keys you can do the following:
for (array_keys($pieces) as $key) {
$yourSiteContent[] =
array('permalink' => $pieces[$key], 'updated' => $pieces2[$key]);
}
You should use a for loop and an indexer, then access each array.
To keep to the foreach format you can also do it like (Assuming both $pieces and $pieces1 have the same keys):
$yourSiteContent = array();
foreach ($pieces as $key=>$value) {
$yourSiteContent[] = array('permalink'=>$value,
'updated'=>$pieces1[$key]);
}
You can use array_combine() to combine the two arrays into a single array, with one being used for keys and the other for values.
foreach (array_combine($pieces, $pieces1) as $id => $id_date) {
$yourSiteContent[] = array('permalink' => $id, 'updated' => $id_date);
}
See array_combine() for more information.

Categories