Take the value from array in php and explode - php

I have this the values of in my array as
$itsthere = (item1-0-100, item2-0-50, item3-0-70, item4-0-50, item5-0-100);
If the user enter the value item3 he has to get 70 which is present in array. I tried alot using explode but its not showing proper value. Can any one help me.

Try with:
$itsthere = array(
'item1-0-100',
'item2-0-50',
'item3-0-70',
'item4-0-50',
'item5-0-100'
);
$search = 'item3';
$output = '';
foreach ( $itsthere as $value ) {
if ( strpos($search . '-', $value) === 0 ) {
$output = explode('-', $value)[2];
break;
}
}

When you say item3 are you refering to the third position or the item3 as array key? I think you can create a assoc array and make item names as key
$isthere = array('item1' => '0-100', 'item2' => '0-50' ,'item3' => '0-70', ....,);
echo $isthere['item3']; // This would give you the value.
If you only want to know if this key is in the array use array_key_exists.

Try this :
$item = 'item3';
$itsthere = array('item1-0-100', 'item2-0-50', 'item3-0-70', 'item4-0-50', 'item5-0-100');
foreach($itsthere as $there)
{
$exp = explode('-',$there);
if($exp[0] == 'item3') {
echo $val = $exp[2];
};
}

Related

How to split evenly and oddly a string to form an array of even and odd results OK Like

I have a php string formed by images and corresponding prices like OK Like
$myString = "ddb94-b_mgr3043.jpg,3800,83acc-b_mgr3059.jpg,4100";
I know that if I do:
$myArray = explode(',', $myString);
print_r($myArray);
I will get :
Array
(
[0] => ddb94-b_mgr3043.jpg
[1] => 3800
[2] => 83acc-b_mgr3059.jpg
[3] => 4100
)
But How could I split the string so I can have an associative array of the form?
Array
(
"ddb94-b_mgr3043.jpg" => "3800"
"83acc-b_mgr3059.jpg" => "4100"
)
Easier way to do like below:-
<?php
$myString = "ddb94-b_mgr3043.jpg,3800,83acc-b_mgr3059.jpg,4100";
$chunks = array_chunk(explode(',', $myString), 2); //chunk array into 2-2 combination
$final_array = array();
foreach($chunks as $chunk){ //iterate over array
$final_array[trim($chunk[0])] = trim($chunk[1]);//make key value pair
}
print_r($final_array); //print final array
Output:-https://eval.in/859757
Here is another approach to achieve this,
$myString = "ddb94-b_mgr3043.jpg,3800,83acc-b_mgr3059.jpg,4100,test.jpg,12321";
$arr = explode(",",$myString);
$temp = [];
array_walk($arr, function($item,$i) use (&$temp,$arr){
if($i % 2 != 0) // checking for odd values
$temp[$arr[$i-1]] = $item; // key will be even values
});
print_r($temp);
array_walk - Apply a user supplied function to every member of an array
Here is your working demo.
Try this Code... If you will receive all the key and value is equal it will work...
$myString = "ddb94-b_mgr3043.jpg,3800,83acc-b_mgr3059.jpg,4100";
$myArray = explode(',', $myString);
$how_many = count($myArray)/2;
for($i = 0; $i <= $how_many; $i = $i + 2){
$key = $myArray[$i];
$value = $myArray[$i+1];
// store it here
$arra[$key] = $value;
}
print_r($arra);

php array key issue with foreach loop and multi-dim arrays

I have listed an example below. What I need is for $key to return the actual index number (position) in the array during the loop, but instead it is returning Array. The same code works fine when given a single dimension array, but not in the example below.
GIVEN:
$screenshots would be similar to the following with only more entries.
Array
(
[0] => Array
(
[screenshot_id] => 871
[image_filename] => DSCF0124.JPG
)
)
PHP:
//build in clause & binding using selected array from above
$prefix = $in_clause = '';
$binding_clause = array();
foreach($screenshots as $key)
{
$in_clause .= $prefix.':selected_'.$key;
$prefix = ', ';
$binding_clause[':selected_'.$key] = $key['screenshot_id'];
}
RESULT:
$inclause = :selected_Array
$binding_clause =
Array
(
[:selected_Array] => 871
)
EXPECTED:
$inclause = :selected_0
$binding_clause =
Array
(
[:selected_0] => 871
)
Just because you call it $key doesn't make it a key. You need the key and the value (inner array):
foreach($screenshots as $key => $value)
{
$in_clause .= $prefix.':selected_'.$key;
$prefix = ', ';
$binding_clause[':selected_'.$key] = $value['screenshot_id'];
}
You need to tell it that you want the KEY and the VALUE.
like this:
foreach($screenshots as $key=>$screenShot)
That will get you the key and the value.
You just need to change your foreach to cast keys and values
foreach($screenshots as $key => $val)
Now the key is in your $key variable while you can access elements with $val array, for example $key['screenshot_id']
You can have a check to documentation examples here
Try:
foreach($screenshots as $key => $screenshot)
{
$in_clause .= $prefix.':selected_'.$key;
$prefix = ', ';
$binding_clause[':selected_'.$key] = $screenshot['screenshot_id'];
}
Read more about PHP foreach: http://php.net/manual/en/control-structures.foreach.php

PHP replace Array values based on certain requirements

I have an array as such:
$array = ["1","0","0","1","1"]
//replace with
$newArray = ["honda","toyota","mercedes","bmw","chevy"]
// only if the original array had a value of "1".
// for example this is my final desired output:
$newArray = ["honda","0","0","bmw","chevy"]
I want to change each value in a specific order IF and only if the array value is equal to "1".
For example the values, "honda", "toyota", "mercedes", "bmw", "chevy" should only replace the array values if the value is "1" otherwise do not replace it and they must be in the right position for example the first element in the array must only be changed to honda, not toyota or any of the other values.
I know I must iterate through the array and provide an if statement as such:
foreach($array as $val) {
if($val == 1){
//do something
} else {
return null;
}
}
Please guide me in the right direction and describe how to replace the values in order, so that toyota cannot replace the first array value only the second position.
You can so something like this - iterating over the array by reference and replacing when the value is 1 (string) and the value in the replace array exists:
foreach($array as $key => &$current) {
if($current === '1' && isset($replace[$key]))
$current = $replace[$key];
}
Output:
Array
(
[0] => honda
[1] => 0
[2] => 0
[3] => bmw
[4] => chevy
)
As per your comment, to output an imploded list of the cars that do have values, you can do something like this - filtering out all zero values and imploding with commas:
echo implode(
// delimiter
', ',
// callback - filter out anything that is "0"
array_filter($array, function($a) {
return $a != '0';
})
);
Currently, our if is asking if $val is true (or if it exists) while your numeric array's values are strings.
Try this:
$array = ["1","0","0","1","1"]
$newArray = ["honda","toyota","mercedes","bmw","chevy"]
foreach($array as $key => $val) {
if($val === '1'){ // if you only want honda
$array[$key] = $newArray[$key];
} else {
return null;
}
}
PHP Code
$array = array("1","0","0","1","1");
$newArray = array("honda","toyota","mercedes","bmw","chevy");
foreach($array as $key => $val) {
if($val === '1')
$array[$key] = $newArray[$key];
}
Would produce the answer you're looking for

foreach integers into array

since im newbie i have a question
well i have $nUserID where store user's id's and is like
int(1)
int(2)
int(1)
and in $nAuctionID i have items id and they are like
int(150022)
int(150022)
int(150031)
i need put it in 1 array and make it like
array (
[1] => 150022
[2] => 120022,150031
)
which user which item id watch
how to do that ?
i though should use foreach , but i cant imagine how will looks
start with
$u[] = $nUserID;
$i[] = $nAuctionID;`
Grouping them by user ID, the following should result in what you're looking for.
$usersWatching = array();
// The following results in:
// array(1 => array(150022, 150023), 2 => array(150022))
// Which should be way more useful.
foreach ($nUserID as $i => $userID)
{
if (!isset($usersWatching[$userID]))
$usersWatching[$userID] = array();
$usersWatching[$userID][] = $nAuctionID[$i];
}
// To get the comma-separated version, do this:
$usersWatching = array_map(function ($value) {
return implode(',', $value);
}, $usersWatching);
this will work :
$arr = array();
foreach( $nUserID as $key=>$value)
{
$arr[$value] = $nAuctionID[$key] ;
}
print_r($arr);
Most confusingly worded question EVA!
$outputArray = array();
for ($i=0; $i< count($nUserID); $i++) {
$outputArray[$nUserID[$i]] = $nAuctionID[$i];
}
echo "<pre>";
print_r($outputArray);
That is what I got from your question..

PHP - Use everything from 1st array, remove duplicates from 2nd?

I have 2 arrays - the first one is output first in full. The 2nd one may have some values that were already used/output with the first array. I want to "clean up" the 2nd array so that I can output its data without worrying about showing duplicates. Just to be sure I have the terminology right & don't have some sort of "array within an array", this is how I access each one:
1st Array
$firstResponse = $sth->fetchAll();
foreach ($firstResponse as $firstResponseItem) {
echo $firstResponseItem['samecolumnname']; // Don't care if it's in 2nd array
}
2nd Array
while( $secondResponseRow = $dbRequest->fetch_assoc() ){
$secondResponseArray = array($secondResponseRow);
foreach ($secondResponseArray as $secondResponseItem){
echo $secondResponseItem['samecolumnname']; //This can't match anything above
}
}
Thanks!
For example:
$response_names = array();
$firstResponse = $sth->fetchAll();
foreach ($firstResponse as $firstResponseItem)
$response_names[] = $firstResponseItem['samecolumnname'];
while( $secondResponseRow = $dbRequest->fetch_assoc() ){
$secondResponseArray = array($secondResponseRow);
foreach ($secondResponseArray as $secondResponseItem) {
if (!in_array($secondResponseItem['samecolumnname'], $response_names))
$response_names[] = $secondResponseItem['samecolumnname'];
}
}
array_walk($response_names, function($value) { echo $value . '<br />' });
If I understand what you're looking to do and the arrays are in the same scope, this should work.
$secondResponseArray = array($secondResponseRow);
$secondResponseArray = array_diff($secondResponseArray, $firstResponse);
//secondResponseArray now contains only unique items
foreach ($secondResponseArray as $secondResponseItem){
echo $secondResponseItem['samecolumnname'];
}
If you know that the keys of duplicate values will be the same you could use array_diff_assoc to get the items of the first array that aren't in the other supplied arrays.
This code
<?php
$a = array('abc', 'def', 'ghi', 'adg');
$b = array('abc', 'hfs', 'toast', 'adgi');
$r = array_diff_assoc($b, $a);
print_r($a);
print_r($r);
produces the following output
[kernel#~]php so_1.php
Array
(
[0] => abc
[1] => def
[2] => ghi
[3] => adg
)
Array
(
[1] => hfs
[2] => toast
[3] => adgi
)
[kernel#~]

Categories