Hello I want create string to array. I have 4 variables:
<?php
$name = "John";
$address = "Moscow";
$born_date = "13-11-1995";
$color = "red";
$join = $name.":".$address.":".$born_date.":".$color;
$array = explode(':', $join);
print_r ($array);
?>
This array result is:
Array ( [0] => John [1] => Moscow [2] => 1995-11-13 [3] => red )
When I change $color variable to null like $color="";
This result like this:
Array ( [0] => John [1] => Moscow [2] => 1995-11-13 [3] => )
I want array number 3 not to show. I want if all $variable == NULL / $variable=="undefined" / $varable=""
Show like this:
Array ( [0] => John [1] => Moscow [2] => 1995-11-13)
The array shows only variable filled.
I'm not sure what your requirements are, but it seems strange to create this array by joining the variables together and then exploding them. You could just add them directly to the array, and add the color conditionally:
$array = array($name, $address, $born_date);
if ($color) {
$array[] = $color;
}
If you need all of the elements to be added conditionally, you can create an array containing all of them and then use array_filter as Rasclatt suggested to eliminate the empty ones.
$array = array($name, $address, $born_date, $color);
$array = array_filter($array);
If it is important that the keys remain sequential, you can use
$array = array_values(array_filter($array));
Related
I have a set of values as a string, like so:
MyCustomProductID1
MyCustomProductID2
Then I proceed to create an array out of these values with explode( "\n", $myProductIdString)
Now I have additional data (strings) that I want to combine with the value from my first array. I want that simple array into a multidimensional one:
Array
(
[0] => Array
(
[id] => MyCustomProductID1
[url] => http://example.com/MyCustomProductID1.jpg
)
[1] => Array
(
[id] => MyCustomProductID2
[url] => http://example.com/MyCustomProductID2.jpg
)
)
How do I get that first array into a multidimensional one and push data along with it?
Instead of direct assigning values to array use loop-
<?php
$str = "MyCustomProductID1
MyCustomProductID2";
$arr = explode("\n", $str);
$result = [];
$url_array = ["http://example.com/MyCustomProductID1.jpg", "http://example.com/MyCustomProductID2.jpg"];
for($i=0;$i<count($arr);$i++){
$result[$i]['id'] = $arr[$i];
$result[$i]['url'] = $url_array[$i];
}
print_r($result);
?>
I have an array with four columns (divided by ";") per index number. The data is coming from a csv file.
Example Data:
John = Firstname
Doe = Lastname
Playground = Description
john.doe#example.com = Email
print_r($dataArray);
Array
(
[0] => John;Doe;Playground;john.doe#example.com
[1] => John;Doe;Playground test;john.doe#example.com
[2] => John;Doe;test Playground;john.doe#example.com
[3] => Johnny;Dawson;Test Area;john.doe#example.com
)
Now I want to remove the duplicates with array_unique.
But I only want to compare the "firstname" and the "lastname".
If the firstname and the lastname has multiple results then remove the duplicate entry.
In this case [1] and [2]
$finalArray = array_unique($dataArray);
array unique will only work if all rows have the same data e.g.
[0] => John;Doe;Playground;john.doe#example.com
[1] => John;Doe;Playground;john.doe#example.com
Goal: Final result
Array
(
[0] => John;Doe;Playground;john.doe#example.com
[1] => Johnny;Dawson;Test Area;john.doe#example.com
)
What is a good way to handle this case?
$a will be unique. notice the array keys that remained the same.
foreach($a as $k=>$v)
{
list($name,$family) = explode(';', $v);
if( isset($temp[$name.$family]) )
unset($a[$k]);
else
$temp[$name.$fam] = true;
}
I'm programming in PHP and I've these arrays:
Category array:
$type = array("fruit","veggie","other");
Subcategory arrays:
$fruit=array("apple","orange");
$veggie=array("bean","pea");
$other=array("bread","cake");
I can get all the elements of the subcategories with:
$all_elements = array_merge($fruit,$veggie,$other);
But this expressions has the problem that if I've to create new categories I've to rewrite the expression.
I'd like to know how I can get an expression like next one to get the same result:
$all_elements = array_merge(SOMETHING($type));
Thanks in advance!!!!!
Take a look at compact:
compact — Create array containing variables and their values
So you want to do:
$type = array("fruit","veggie","other");
$fruit=array("apple","orange");
$veggie=array("bean","pea");
$other=array("bread","cake");
print_r(compact(($type)));
OUTPUT
Array
(
[fruit] => Array
(
[0] => apple
[1] => orange
)
[veggie] => Array
(
[0] => bean
[1] => pea
)
[other] => Array
(
[0] => bread
[1] => cake
)
)
However, I recommend you to do it completly differently, as #Rasclatt suggested:
$food['fruit'][] = 'apple';
$food['fruit'][] = 'orange';
$food['veggie'][] = 'bean';
$food['veggie'][] = 'pea';
$food['other'][] = 'bread';
$food['other'][] = 'cake';
I think I would create one array that you can add to. You can more easily merge and handle new categories. You can loop through the array to get types and sub-types.
$food['fruit'][] = 'apple';
$food['fruit'][] = 'orange';
$food['veggie'][] = 'bean';
$food['veggie'][] = 'pea';
$food['other'][] = 'bread';
$food['other'][] = 'cake';
I would layout the data differently:
$item["fruit"]=array("apple","orange");
$item["veggie"]=array("bean","pea");
$item["other"]=array("bread","cake");
So if you want $all_elements you could just ask for $item instead:
print_r ($item);
And if you want a certain category:
print_r ($item["veggie"]);
With the following array, how would I just print the last name?
Preferably I'd like to put it in the format print_r($array['LastName']) the problem is, the number is likely to change.
$array = Array
(
[0] => Array
(
[name] => FirstName
[value] => John
)
[1] => Array
(
[name] => LastName
[value] => Geoffrey
)
[2] => Array
(
[name] => MiddleName
[value] => Smith
)
)
I would normalize the array first:
$normalized = array();
foreach($array as $value) {
$normalized[$value['name']] = $value['value'];
}
Then you can just to:
echo $normalized['LastName'];
If you are not sure where the lastname lives, you could write a function to do this like this ...
function getValue($mykey, $myarray) {
foreach($myarray as $a) {
if($a['name'] == $mykey) {
return $a['value'];
}
}
}
Then you could use
print getValue('LastName', $array);
This array is not so easy to access because it contains several arrays which have the same key. if you know where the value is, you can use the position of the array to access the data, in your case that'd be $array[1][value]. if you don't know the position of the data you need you would have to loop through the arrays and check where it is.. there are several solutions to do that eg:
`foreach($array as $arr){
(if $arr['name'] == "lastName")
print_r($arr['value']
}`
Can someone please put me out of my misery and explain why I'm missing the middle value when I try to push the results of a preg_match into another array? It's either something silly or a vast gap in my understanding. Either way I need help. Here is my code:
<?php
$text = 'The group, which gathered at the Somerfield depot in Bridgwater, Somerset,
on Thursday night, complain that consumers believe foreign meat which has been
processed in the UK is British because of inadequate labelling.';
$word = 'the';
preg_match_all("/\b" . $word . "\b/i", $text, $matches, PREG_OFFSET_CAPTURE);
$word_pos = array();
for($i = 0; $i < sizeof($matches[0]); $i++){
$word_pos[$matches[0][$i][0]] = $matches[0][$i][1];
}
echo "<pre>";
print_r($matches);
echo "</pre>";
echo "<pre>";
print_r($word_pos);
echo "</pre>";
?>
I get this output:
Array
(
[0] => Array
(
[0] => Array
(
[0] => The
[1] => 0
)
[1] => Array
(
[0] => the
[1] => 29
)
[2] => Array
(
[0] => the
[1] => 177
)
)
)
Array
(
[The] => 0
[the] => 177
)
So the question is: why am I missing the [the] => 29? Is there a better way? Thanks.
PHP arrays are 1:1 mappings, i.e. one key points to exactly one value. So you are overwriting the middle value since it also has the key the.
The easiest solution would be using the offset as the key and the matched string as the value. However, depending on what you want to do with the results a completely different structure might be more appropriate.
First you assign $word_pos["the"] = 29 and then you OVERWRITE IT with $word_pos["the"] = 177.
You don't overwrite The because indexes are case sensitive.
So maybe use an array of objects like this:
$object = new stdClass;
$object->word = "the"; // for example
$object->pos = 29; // example :)
and assign it to an array
$positions = array(); // just init once
$positions[] = $object;
alternatively you can assign an associative array instead of the object, so it would be like
$object = array(
'word' => 'the',
'pos' => 29
);
OR assign the way you do, but instead of overwriting, just add it to an array, like:
$word_pos[$matches[0][$i][0]][] = $matches[0][$i][1];
instead of
$word_pos[$matches[0][$i][0]] = $matches[0][$i][1];
so you get something like:
Array
(
[The] => Array
(
[0] => 0
)
[the] => Array
(
[0] => 29
[1] => 177
)
)
Hope that helps :)
What is happening actually :
when i=0,
$word_pos[The] = 0 //mathches[0][0][0]=The
when i=1
$word_pos[the] = 29
when i=3
$word_pos[the] = 177 //here this "the" key overrides the previous one
//so your middle 'the' is going to lost :(
Now an array based solution can be like this :
for($i = 0; $i < sizeof($matches[0]); $i++){
if (array_key_exists ( $matches[0][$i][0] , $word_pos ) ) {
$word_pos[$matches[0][$i][0]] [] = $matches[0][$i][1];
}
else $word_pos[$matches[0][$i][0]] = array ( $matches[0][$i][1] );
}
Now if you dump $word_pos the output should be :
Array
(
[The] => Array
(
[0] => 0
)
[the] => Array
(
[0] => 29 ,
[1] => 177
)
)
Hope that helps.
Reference : array_key_exist